繁体   English   中英

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

[英]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访问该属性,并且不会继承到实例,因为实例继承自Person.prototype 因此,如果您为此添加一个属性,例如Person.prototype.hairColor ,那么它将被继承并且可以通过实例( myPerson.hairColor )访问。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM