Why does the JavaScript "writable" property descriptor not forbid any property changes?

For example:

var TheDarkKnight = Object.create(Superhero, {
    "name": {
        value:"Batman",
        writable:"false"
    }
});

TheDarkKnight.name; //"Batman";

TheDarkKnight.name = "Superman";
TheDarkKnight.name; //"Superman";

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?

有帮助吗?

解决方案

It should be false, not "false". In other words, it should be a boolean.

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";

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top