Does Javascript writable descriptor prevent changes on instances?

前端 未结 3 651
故里飘歌
故里飘歌 2020-12-11 20:54

Answers (please read them below, their respective authors provided valuable insights):

  • \"writable: false\" prevents assigning a new value,
3条回答
  •  眼角桃花
    2020-12-11 21:33

    You cannot write to an instance property if its prototype defines that property as unwritable (and the object instance doesn't have a descriptor) because the set operation goes up to the parent (prototype) to check if it can write, even though it would write to the child (instance). See EcmaScript-262 Section 9.1.9 1.c.i

    4. If ownDesc is undefined, then
      a. Let parent be O.[[GetPrototypeOf]]().
      b. ReturnIfAbrupt(parent).
      c. If parent is not null, then
          i. Return parent.[[Set]](P, V, Receiver).
    

    However, if you are trying to get around that, you can set the descriptor of the instance itself.

    var proto = Object.defineProperties({}, {
      foo: {
        value: "a",
        writable: false,  // read-only
        configurable: true  // explained later
      }
    });
    
    var instance = Object.create(proto);
    Object.defineProperty(instance, "foo", {writable: true});
    instance.foo // "b"
    

提交回复
热议问题