Object.defineProperty 有时会抛出

Object.defineProperty sometimes throws

我正在玩 ES6 类 和不可写属性。例如,我有以下代码。我是运行它在节点版本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>'

所以看起来如果从实例外部设置一个只读实例属性,赋值会被忽略;如果从实例内部设置,则为 TypeError。

这是预期的行为吗?我在任何地方都找不到它的记录。

不同之处在于 ,而您的代码的其余部分显然是草率的。尝试

(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);
}());

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

是,在非严格模式下

读这个: Modifying a property

在严格模式下会抛出错误:

'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