Does Javascript writable descriptor prevent changes on instances?

前端 未结 3 644
故里飘歌
故里飘歌 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:23

    Yes, this is expected behaviour.

    it fails silently.

    Not exactly. Or: Only in sloppy mode. If you "use strict" mode, you'll get an

    Error { message: "Invalid assignment in strict mode", … }
    

    on the line test4.answer = function() { return 0; };

    it can be overloaded on the prototype of a subclass (test2), but not an instance of a subclass (test4)

    This has nothing to do with instances vs. prototypes. What you didn't notice is that you're using different ways to create the overloading property:

    • an assignment to a property that is inherited and non-writable fails
    • an Object.defineProperty call just creates a new property, unless the object is non-extensible

    You can do the same for your instance:

    Object.defineProperty(test4, "answer", {
        value: function() { return 42; }
    });
    

提交回复
热议问题