在下面的代码中,
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.planet = "Earth";
p1 = new Person("David", "Beckham", 39);
p2 = new Person("Lionel", "Messi", 30);
如果有多个实例
p1
p2
使用构造函数 Person
创建, 然后我如何理解属性的区别
planet
有属性(property)age
?添加属性 planet
会有什么不同?如this.planet
在构造函数中Person
?注:了解
prototype
属性(property)
最佳答案
考虑将来我们要更改所有实例共享的原型(prototype)属性的情况
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.planet = "Earth";
p1 = new Person("David", "Beckham", 39);
p2 = new Person("Lionel", "Messi", 30);
console.log(p1.planet) // Earth
Person.prototype.planet = "Mars"
console.log(p1.planet) // Mars
console.log(p1.planet === p2.planet) // true
更改原型(prototype)上的一个属性将在所有情况下更改它
关于javascript - 实例属性与原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32114191/