gpt4 book ai didi

javascript - 无法更改对象属性值

转载 作者:行者123 更新时间:2023-11-30 12:13:30 24 4
gpt4 key购买 nike

我是 Javascript 的新手,我试过这个:

object1 = {};
object2 = Object.create(object1, {a:{value:1}});
object2.a = 2;

然后如果我显示 object2.a,它仍然是 1 而不是 2。这是为什么?

谢谢。

最佳答案

因为 Object.create() 不是你想的那样。

看这个ECMAScript 5: Object creation and property definition

There are three additional aspects of a property we can control, each given a boolean value:

  1. writable: Controls whether or not the property can be assigned. If false, attempts at assignment will fail. Only applies to data descriptors.
  2. enumerable: Controls whether or not this property will appear in for...in loops.
  3. configurable: Controls whether or not the property can be deleted, and whether its property descriptor (other than writable) can be changed.

Each of these defaults to false if not supplied.

所以你需要的是:

var object1 = {};
var object2 = Object.create(object1, {
a: {
value: 1,
writable: true
},
});
object2.a = 2;

玩得开心:)

关于javascript - 无法更改对象属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092515/

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