我正在阅读 John Resig 在 new ES5 features 上的一篇博客,一个是 Object
描述符。约翰在他的博客早些时候写道:
The three attributes (writable, enumerable, and configurable) are all optional and all default to true. Thus, the only property that you’ll need to provide will be, either, value or get and set.
稍后他提供了一个例子:
var obj = {};
Object.defineProperty( obj, "propertyname", {
value: true,
writable: false,
enumerable: true,
configurable: true
});
(function() {
var name = "John";
Object.defineProperty( obj, "name", {
get: function(){ return name; },
set: function(value){ name = value; }
});
})();
但是,当检查 name
的属性描述符时,它不可配置或可枚举,因此我无法在 for 循环中访问它。
console.log(Object.getOwnPropertyDescriptor(obj, 'name'))
> Object {enumerable: false, configurable: false}
name
不应该既可枚举又可配置吗?我在这里缺少什么?
最佳答案
来自 the spec ,数据属性默认是不可配置、不可枚举和不可写的。
If the initial values of a property's attributes are not explicitly specified by this specification, the default value defined in Table 4 is used.
Table 4: Default Attribute Values
┌──────────────────┬─────────────────┐ │ Attribute Name │ Default Value │ ├──────────────────┼─────────────────┤ │ [[Value]] │ undefined │ │ [[Get]] │ undefined │ │ [[Set]] │ undefined │ │ [[Writable]] │ false │ │ [[Enumerable]] │ false │ │ [[Configurable]] │ false │ └──────────────────┴─────────────────┘
但是,当您通过赋值创建数据属性时,CreateDataProperty将其定义为可配置、可枚举和可写。
Let newDesc be the PropertyDescriptor{[[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}.
关于JavaScript 描述符 : enumerable/configurable/writable are not true by default?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41707191/