为什么我们不能像向现有对象添加新的 属性 一样向对象构造函数添加新的 属性?

Why we cannot add a new property to an object constructor the same way we add a new property to an existing object?

我在 javascript 中有一个函数。

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.name = function() {return this.firstName + " " + this.lastName;};
}

为什么我们不能像这样在 javascript 中的构造函数中添加一个 属性?

Person.hairColor = "black";

我们可以像这样轻松地向对象添加一个属性。

myPerson = new Person("firstName","lastName",23,"brown");
myPerson.hairColor = "black";

为什么第一个不行,为什么javascript限制在构造函数中添加一个属性?

可以使用prototype来添加。示例:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.name = function() {return this.firstName + " " + this.lastName};
}

Person.prototype.hairColor = "black";

myPerson = new Person("firstName","lastName",23,"brown");
console.log(myPerson.hairColor); // black

如果将 属性 分配给 Person.hairColor,则只能通过 Person.hairColor 访问,并且不会继承到实例,因为实例继承自 [=13] =].因此,如果您向其中添加一个 属性,例如Person.prototype.hairColor,那么它将被继承并可以通过实例访问 (myPerson.hairColor)。

请注意,设置 myPerson.hairColor 不会更改原型中的值,但会在实例上创建一个新的 属性,例如:

  myPerson.hairColor += " and brown";
  console.log(
     Person.prototype.hairColor, // "black"
     myPerson.hairColor, // "black and brown"
  );