gpt4 book ai didi

javascript - Object.create 中的对象属性值是常量吗?

转载 作者:行者123 更新时间:2023-12-02 23:16:10 26 4
gpt4 key购买 nike

这是一个非常好奇的问题,我一直在学习一些 JavaScript 并且我的代码可以工作,但我想了解为什么会发生这种情况:

为什么当 att 和 def boost 在 Object.create 外部创建时我可以使其工作,但属性 hp 却作为常量工作?

let Pokemon = {
def: this.def,
att: this.att,
defBoost: function() {
this.def = this.def + this.def
return this.def;
},
attBoost: function() {
this.att = this.att + this.att
return this.att;
},
hpBoost: function() {
this.hp = this.hp + this.hp
return this.hp;
}

}

let psyduck = Object.create(Pokemon, {
name: {
value: "Psyduck"
},
hp: {
value: 500
}
});

psyduck.def = 12;
psyduck.att = 20;

console.log(psyduck);

psyduck.attBoost();
psyduck.defBoost();
psyduck.hpBoost();

console.log(psyduck);

最佳答案

当您使用 descriptor 定义属性时,就像在 Object.definePropertiesObject.create 中一样,您未指定的所有属性都默认为 false。所以当你有

hp: { value: 500}

它的作用就像

hp: {
value: 500,
enumerable: false,
writable: false,
}

writable: false 表示该属性是只读的。

另一方面,当通过赋值创建属性时,enumerablewritable 都默认为 true

此外,请确保始终写入 strict mode因此分配给只读属性会引发错误,而不是默默地失败!

关于javascript - Object.create 中的对象属性值是常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155550/

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