在JavaScript中,如果我分配给具有getter但没有setter的对象属性会发生什么?

use*_*783 1 javascript properties object getter-setter

在以下代码中,两者都使用console.log(o.x)print 1.任务会o.x = 2怎样?它被忽略了吗?

var o = {
    get x() {
        return 1;
    }
}

console.log(o.x);  // 1
o.x = 2
console.log(o.x);  // 1
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

在草率模式中,是的,它只会被忽略 - "已分配"的值将被丢弃.但在严格模式下(建议使用),将抛出以下错误:

未捕获的TypeError:无法设置属性x #<Object>只有一个getter

'use strict';
var o = {
    get x() {
        return 1;
    }
}

console.log(o.x);  // 1
o.x = 2
Run Code Online (Sandbox Code Playgroud)