gpt4 book ai didi

javascript - 在 JavaScript 中更改元数据是如何工作的?

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

在控制台中,我得到 abc尽管设置 {writable:false} .您能解释一下更改元数据的工作原理吗?

let portfolio = {
myFirstName: "Bob",
myLastName: "Alice",
myAge: 26,
aboutMe: function() {
return ("First Name: " + this.myFirstName + "; Last Name: " + this.myLastName + "; Age: " + this.myAge + ";");
}
};
Object.defineProperty(portfolio, "myFirstName", { writable: false });
Object.defineProperty(portfolio, "myFirstName", { value: "abc" });
console.log(portfolio.myFirstName);

最佳答案

在你的第二行 Object.defineProperty(portfolio, "myFirstName", { value: "abc" });您正在再次定义该属性。
您没有分配值。您正在扔掉旧房产并用全新的品牌取而代之。 (技术上不正确,它经历了很多步骤到 evaluate and apply values to property properties ,但为了简单理解,我相信这足以理解,因为在这种情况下感觉像是一个新的。如果你想拥有复杂的,请阅读链接真相)
要分配新值,请使用 portfolio.myFirstName = "value here"你会看到它被写保护了。

let portfolio = {
myFirstName: "Bob",
myLastName: "Alice",
myAge: 26,
aboutMe: function() {
return ("First Name: " + this.myFirstName + "; Last Name: " + this.myLastName + "; Age: " + this.myAge + ";");
}
};
Object.defineProperty(portfolio, "myFirstName", { writable: false });
portfolio.myFirstName = "Alice";
console.log(portfolio.myFirstName);

为防止出现这种变通方法,请调用 Object.freeze()修改其属性后在对象上。这也会产生其他副作用,例如无法编辑其他属性的值。

let portfolio = {
myFirstName: "Bob",
myLastName: "Alice",
myAge: 26,
aboutMe: function() {
return ("First Name: " + this.myFirstName + "; Last Name: " + this.myLastName + "; Age: " + this.myAge + ";");
}
};
Object.defineProperty(portfolio, "myFirstName", { writable: false });
Object.freeze(portfolio);
Object.defineProperty(portfolio, "myFirstName", {value:"abc"});
console.log(portfolio.myFirstName);

关于javascript - 在 JavaScript 中更改元数据是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65611831/

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