JavaScript 描述符 : enumerable/configurable/writable are not true by default?

标签 javascript descriptor

我正在阅读 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/

相关文章:

python - 如何在 Python 中使用自定义描述符为类生成 __init__?

javascript - 带偏移的边栏不起作用。我做错了什么?

javascript - JSON.stringify 给出了错误的索引结构

javascript - 将所选值与 DevExtreme 和 KnockOut 绑定(bind)时出错

javascript - 使 hover resize 元素只影响元素

python __get__ 方法

c++ - directx-12 - 如何使用具有多个描述符堆的命令列表?

c# - 如何要求确认删除 list 项目?

javascript - 不评估访问器检测 Object.defineProperty 是否具有链式数据描述符

python - Python 描述符的 __set__ 可以用 instance = None 调用吗?