当我用对象文字添加原型属性时,上游直接原型属性就会中断.为什么?

When I add prototype properties with an object literal then upstream direct protoype properties break. Why?

本文关键字:原型 属性 为什么 中断 对象 文字 添加      更新时间:2023-09-26

这似乎取决于原型声明的顺序。这是代码:

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);

这里有一个链接:https://jsfiddle.net/tdz0yrs2/

这类语句:

Person.prototype = {
  // ...
};

将构造函数的prototype属性重置为一个全新的对象。在此点之前设置的任何属性都将保留在原型对象上,但不会出现在新构建的对象中。

这里的关键是,像这样的对象文字赋值不会添加属性—它创造了一个全新的对象。

Pointy也这么说。

您需要在不覆盖整个对象的情况下将新功能添加到原型中:

Person.prototype.someFunction = function() { ... };

或者使用下划线的extend之类的东西将新属性混合到现有原型中:

_.extend(Person.prototype, { 
    // ...
});