Search code examples
javascriptnode.jstypeerrordefineproperty

Object.defineProperty sometimes throws


I am playing with ES6 classes and non-writable properties. As an example, I have the following code. I am running it under node version v9.9.0.

  Crash = class Crash {
    constructor() {
      Object.defineProperty(this, 'test', {
        enumerable: true,
        value: 100
      });
    }

    setTest(val) {
      this.test = val;
    }

  };

  c = new Crash;
  c.test = 10;    // happens silently
  console.log(c); // displays Crash { test: 100 }
                  // so it didn't change
  c.setTest(20);  // Throws a typeError
  
  // TypeError: Cannot assign to read only property 'test' of object '#<Crash>'

So it seems that if a read-only instance property is set from outside the instance, the assignment is ignored; if set from inside the instance, it's a TypeError.

Is this expected behaviour? I can't find it documented anywhere.


Solution

  • Is this expected behaviour? I can't find it documented anywher

    Yes, in non strict mode

    Read this: Modifying a property

    In strict mode the error will be thrown:

    'use strict'; // <------- Strict mode
    
    class Crash {
      constructor() {
        Object.defineProperty(this, 'test', {
          enumerable: true,
          value: 100
        });
      }
    
      setTest(val) {
        this.test = val;
      }
    };
    
    var c = new Crash;
    c.test = 10; // happens silently