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

时间:2019-07-15 10:10:41

标签: javascript object constructor

我在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限制了向构造函数添加属性?

2 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:1)

如果您将属性分配给Person.hairColor,则只能通过Person.hairColor访问该属性,并且该属性将不会继承到实例,因为实例是从Person.prototype继承的。因此,如果您向其中添加属性,例如Person.prototype.hairColor,那么它将被继承并且可以通过实例(myPerson.hairColor)进行访问。

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

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