代码如下:原型是它的构造函数的一个实例吗?
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