Cliff Stanford
Cliff Stanford

Reputation: 614

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.

Upvotes: 2

Views: 419

Answers (2)

Ele
Ele

Reputation: 33726

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

Upvotes: 1

Bergi
Bergi

Reputation: 665185

The difference is that your class method is in strict mode, while the rest of your code is implicitly sloppy. Try

(function() {
  "use strict";
  const c = new Crash;
//^^^^^ needs declaration for not failing here alredy
  c.test = 10;    // Throws a TypeError as expected
  console.log(c);
}());

Upvotes: 3

Related Questions