我正在使用 ES6 类和不可写属性。作为示例,我有以下代码。我在 Node 版本 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>'
因此,如果从实异常(exception)部设置只读实例属性,则分配将被忽略;如果从实例内部设置,则会出现 TypeError。
这是预期的行为吗?我在任何地方都找不到它的记录。
最佳答案
不同的是 your class
method is in strict mode ,而您的其余代码则隐含地很草率。尝试一下
(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);
}());
关于javascript - Object.defineProperty 有时会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49493578/