代碼如下:原型是它的構造函數的一個實例嗎?
function Teacher(name, age) {
this.name = name;
this.age = age;
}
Teacher.prototype.sayName = function() {
alert(this.name);
};
Teacher.prototype.sayHi = function() {
alert("Hi, I'm " + this.name);
};
console.log(Teacher.prototype instanceof Teacher); // false
console.log(Teacher.prototype instanceof Object); // true
console.log(Teacher.prototype); // Teacher {sayName: function, sayHi: function}
p.s.上面的輸出是鉻。 第一個console.log顯示Teacher.prototype不是Teacher的一個實例,但是第三個顯示Teacher.prototype是Teacher的一個實例(直觀地),這是矛盾的。
我知道第二個console.log是真的,因爲Object.prototype在Teacher.prototype的原型鏈中,正好是Teacher.prototype.__proto__ === Object.prototype
。因此,第一個console.log應該輸出false。
但我很困惑爲什麼輸出第三個console.log顯示Teacher.prototype是Teacher的一個實例。任何人都可以爲我澄清?非常感謝。
是的,看起來就是這樣。如果將其覆蓋到'Teacher.prototype.constructor = Array',則在執行'Teacher.prototype'時,它將在控制檯中使用'Array'。 – 2013-04-29 18:04:18