我最近开始使用Object.create和类似的ES5来玩(和工作)。我不太了解Object属性的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
}
}
});
答案 0 :(得分:0)
你有一个错字。该标准将属性定义为writable
,而不是writeable
。修复b
定义中的拼写,它完美无缺:
b: {
value: 'value configured, but writeable',
writable: true
}