JS:理解可写为 Object 属性属性

JS: understanding writeable as Object property attribute

本文关键字:属性 Object JS      更新时间:2023-09-26

我最近开始玩(和工作)Object.create和类似的ES5东西。我不太了解对象属性的writeable属性的工作方式。规范说,默认情况下设置为 false,但是如何在不使用 getter 和 setter 的情况下更改它?

或者:为什么像它一样工作这段代码:

编辑:此代码是垃圾!我还不明白 getter 和 setter 在这里是如何工作的!

var ob = Object.create(Object.prototype, {
    a: { 
        value: 'not save'
     },
     b: {
        value: 'value configured, but writeable',
        writeable: true
    },
    c: {
        configurable: false,
        get: function() {
            return c;
        },
        set: function(string) {
            c = string;
        }
    }
});
ob.c = 'set d the first time'; //not doing this would give us an error in the console.log line (access to ob.c)
console.log(ob.a, ob.b, ob.c); //->not save value configured, but writeable set d the first time
ob.a = 'new a';
ob.b = 'new b';
ob.c = 'new c';
console.log(ob.a, ob.b, ob.c, ob.d); //->not save value configured, but writeable new c

为什么实际上只有 ob.c 是可写的,而不是 ob.b - 或者我做错了什么?

编辑:更好的代码在这里

var ob = Object.create(Object.prototype, {
    a: { 
        value: 'not save',
     },
     b: {
        value: 'value configured, but writeable',
        writeable: true
    },
    c: {
        configurable: false,
        get: function() {
            return this.a; // works, but is not useful because of the naming and a is not writeable
        },
        set: function(string) {
            this.a = string; // works, but is not useful because of the naming and a is not writeable
        }
    }
});

你有一个错别字。该标准将属性定义为writable,而不是writeable。修复b定义中的拼写,它非常有效:

 b: {
    value: 'value configured, but writeable',
    writable: true
}