为什么我不能在Javascript对象中重新定义属性? [英] Why can't I redefine a property in a Javascript object?
问题描述
我正在使用 Object.create
创建一个对象,我想为其添加属性。
I am creating a object using Object.create
and I want to add properties to it.
> var o = Object.create({});
undefined
> Object.defineProperty(o, "foo", {value: 43, enumerable: true});
{foo: 43}
> o
{foo: 43}
> o.foo
43
> for (var i in o) { console.log(i); }
foo
> Object.keys(o)
['foo']
> Object.defineProperty(o, "foo", {value: 43, enumerable: false });
TypeError: Cannot redefine property: bar
Q1)为什么我不能重新定义属性?
Q1) Why can't I redefine the property ?
> o.__proto__
{}
> o.prototype
undefined
Q2)为什么原型是空的?为什么这两个值不同,即 {}
vs undefined
?
Q2) Why is the prototype empty ? And why are these 2 values different i.e. {}
vs undefined
?
推荐答案
您无法重新定义属性,因为 Object.defineProperty()
默认为不可配置的属性,来自< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\"rel =noreferrer> docs :
You are unable to redefine the property because Object.defineProperty()
defaults to non-configurable properties, from the docs:
可配置
configurable
当且仅当此属性描述符的类型可能被更改且属性为true时才为true可以从相应的对象中删除。
默认为false。
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.
所以这默认为false - 你需要传递它可配置:true
允许它。
So this defaults to false - you'd need to pass it configurable: true
to allow it.
这篇关于为什么我不能在Javascript对象中重新定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!