JavaScript如何“可写”属性描述符工作? [英] How does JavaScript "writable" property descriptor work?
问题描述
为什么JavaScript可写属性描述符不禁止任何属性更改?
Why does the JavaScript "writable" property descriptor not forbid any property changes?
例如:
var TheDarkKnight = Object.create(Superhero, {
"name": {
value:"Batman",
writable:"false"
}
});
TheDarkKnight.name; //"Batman";
TheDarkKnight.name = "Superman";
TheDarkKnight.name; //"Superman";
我认为 TheDarkKnight.name
仍应返回蝙蝠侠
我尝试将其更改为其他值后,因为我将可写属性描述符设置为 false
。
I thought TheDarkKnight.name
should still return "Batman"
after I tried to change it to another value because I set the "writable" property descriptor to false
.
那么如何以正确的方式使用它?
So how to use it in the right way?
推荐答案
它应该是 false
,而不是false
。换句话说,它应该是一个布尔值。
It should be false
, not "false"
. In other words, it should be a boolean.
如果你没有传递一个布尔值,那么你提供的任何值都将被强制转换为布尔值,并且 Boolean(false)=== true; // true
,所以你实际上传递了 writable:true
。
If you don't pass a boolean, then whatever value you give will be coerced to a boolean, and Boolean("false") === true; // true
, so you were effectively passing writable:true
.
var TheDarkKnight = Object.create(Superhero, {
"name": {
value:"Batman",
writable:false // boolean false (or any falsey value)
}
});
TheDarkKnight.name; //"Batman";
TheDarkKnight.name = "Superman";
TheDarkKnight.name; //"Batman";
另外,请注意 writable:false
是默认值,因此如果您只是从描述符中删除该设置,该属性将不可写。
Also, note that writable:false
is the default value, so if you just remove that setting from the descriptor, the property will not be writable.
这篇关于JavaScript如何“可写”属性描述符工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!