对象原型在JavaScript中被复制或引用



在以下代码中:

let user = {
name: "John",
surname: "Smith",
set fullName(value) {
[this.name, this.surname] = value.split(" ");
},
get fullName() {
return `${this.name} ${this.surname}`;
}
};
let admin = {
__proto__: user,
isAdmin: true
};
alert(admin.fullName); // John Smith (*)
// setter triggers!
admin.fullName = "Alice Cooper"; // (**)
alert(admin.fullName); // Alice Cooper, state of admin modified
alert(user.fullName); // John Smith, state of user protected

用户对象是管理对象的原型,正如我们所看到的,行(**(设置了adminObject的fullName,尽管userObject仍然是原来的样子。

那么说用户Properties&方法是否被复制到管理对象?

使用Object.getOwnPropertyNames表明,使用admin.fullName = "Alice Cooper"实际上可以创建新属性,而不是覆盖任何内容。

let user = {
name: "John",
surname: "Smith",
set fullName(value) {
[this.name, this.surname] = value.split(" ");
},
get fullName() {
return `${this.name} ${this.surname}`;
}
};
let admin = {
__proto__: user,
isAdmin: true
};
console.log(Object.getOwnPropertyNames(admin));
admin.fullName = "Alice Cooper";
console.log(Object.getOwnPropertyNames(admin));
console.log(Object.getOwnPropertyNames(user));

改变原型的属性表明它引用了

let user = {
name: "John",
surname: "Smith",
set fullName(value) {
[this.name, this.surname] = value.split(" ");
},
get fullName() {
return `${this.name} ${this.surname}`;
}
};
let admin = {
__proto__: user,
isAdmin: true
};
console.log(admin);
user.fullName = "Alice Cooper";
console.log(admin);
console.log(user);

最新更新