gpt4 book ai didi

javascript - 实例属性与原型(prototype)属性

转载 作者:行者123 更新时间:2023-12-03 12:24:02 25 4
gpt4 key购买 nike

在下面的代码中,

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com