有两个代码。
为什么第一个正确,而第二个则不正确?
this.prototype
有什么问题?
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
if (typeof this.sayName != "function"){
Person.prototype.sayName = function(){
alert(this.name);
};
}
}
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
if (typeof this.sayName != "function"){
this.prototype.sayName = function(){
alert(this.name);
};
}
}
它们两个实际上都是不正确的。但稍后再详细介绍。
第二个是不正确的,因为对象没有prototype
属性。只有 functions 具有这样的属性。
在第二个示例中,this
是一个对象,因此this.prototype
是undefined
。在第一个示例中,您设置了Person.prototype
,而Person
是一个函数,因此所有功能都是"好"。
为什么第一个示例仍然错了?因为您通常没有理由扩展构造函数内部原型对象。构造函数应仅包含实例特定代码,并且原型对象应在所有情况下持有共享的属性。
因此,您的上面示例正确写为:
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function(){
alert(this.name);
};
这是关于如何实现原型的。
说person.prototype.sayname'person.protype'为您提供[Prototype]的属性。
调用this.prototype.sayname时,检查了一个名为"原型"的属性,以" this"对象检查,如果找不到[[[prototype]]]属性的" this"的属性,这仍然没有找到,因为您避免了定义它
P.S。
尚未对自己进行测试,但是这个.__ proto__应在某些实现中起作用
在this.prototype
中,您是指该实例。该实例没有原型,构造函数函数确实如此。您可以替换:
if (typeof this.sayName != "function"){
this.prototype.sayName = function(){
alert(this.name);
};
}
if (!Person.prototype.sayName) {
Person.prototype.sayName = function(){
alert(this.name);
};
}
在所有派生实例中都存在分配给原始Pe的方法。第一个摘要中的this.sayName
在第一个实例化中不存在,但是您的if ...
捕获并分配Person.prototype.sayName
,随后可用于Person
的新实例。这就是第一个示例有效的原因。