Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

How does changing metadata in JavaScript work?

In the console, I get abc despite setting {writable:false}. Could you explain how changing metadata works?

let portfolio = {
  myFirstName: "Bob",
  myLastName: "Alice",
  myAge: 26,
  aboutMe: function() {
    return ("First Name: " + this.myFirstName + "; Last Name: " + this.myLastName + "; Age: " + this.myAge + ";");
  }
};
Object.defineProperty(portfolio, "myFirstName", { writable: false });
Object.defineProperty(portfolio, "myFirstName", { value: "abc" });
console.log(portfolio.myFirstName);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

writable: false only has an effect on Object.defineProperty if configurable is also set to false. See step 7 of the ValidateAndApplyPropertyDescriptor algorithm:

Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true, then
  If current.[[Configurable]] is false and current.[[Writable]] is false, then
    If Desc.[[Writable]] is present and Desc.[[Writable]] is true, return false.
    If Desc.[[Value]] is present and SameValue(Desc.[[Value]], current.[[Value]]) is false, return false.
    Return true.

That's likely because as long as a property is configurable, nothing stops you from changing the value of writable back to true, e.g.

Object.defineProperty(
  portfolio,
  "myFirstName",
  {value: "abc", writable: true}
);

Note that any property declared as part of an object literal automatically has {writable: true, configurable: true, enumerable: true}.

Examples

Can't assign because writable and configurable are both false:

var obj = {};
Object.defineProperty(obj, 'test', {
  value: 42,
  configurable: false,
  writable: false,
  enumerable: true,
});
console.log(obj);
Object.defineProperty(obj, 'test', {value: 21});
console.log(obj);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...