我在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限制将属性添加到构造函数中?
发布于 2019-07-15 10:22:47
如果将属性分配给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"
);
发布于 2019-07-15 10:21:40
您可以使用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
https://stackoverflow.com/questions/57037585
复制相似问题