Javascript 当我添加带有对象文字的原型属性时,上游直接原型属性中断。为什么?
这似乎取决于原型声明的顺序。代码如下:Javascript 当我添加带有对象文字的原型属性时,上游直接原型属性中断。为什么?,javascript,Javascript,这似乎取决于原型声明的顺序。代码如下: function Person(firstname){ this.firstname = firstname; } //Person.prototype.middlename = "Charles"; //this line doesn't work here Person.prototype = { constructor: Person, lastname: "Claus" } Person.prototype.
function Person(firstname){
this.firstname = firstname;
}
//Person.prototype.middlename = "Charles"; //this line doesn't work here
Person.prototype = {
constructor: Person,
lastname: "Claus"
}
Person.prototype.middlename = "Charles"; //this line works here
var person1 = new Person("Santa");
console.log(person1.firstname, person1.middlename, person1.lastname);
以下是一个链接:
这种说法:
Person.prototype = {
// ...
};
将构造函数的prototype属性重置为一个全新的对象。在该点之前设置的任何属性都将保留在旧原型对象上,但对于新构造的对象将不存在
这里的关键点是,像这样的对象文字赋值不会添加属性,而是创建一个全新的对象。正如Pointy所说 您需要在不覆盖整个对象的情况下向原型添加新函数:
Person.prototype.someFunction = function() { ... };
或者使用类似于“sextend
的方法将新属性混合到现有原型中:
_.extend(Person.prototype, {
// ...
});
因为你正在用一个全新的对象覆盖原型。旧原型上存在第一个中间名属性,但您在下一行替换了该对象。谢谢大家。这很有道理。