In JavaScript, what happens if I assign to an object property that has a getter but no setter?

社会主义新天地 提交于 2019-12-24 17:16:03

问题


In the following code, both uses of console.log(o.x) print 1. What happens to the assignment o.x = 2? Is it just ignored?

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

console.log(o.x);  // 1
o.x = 2
console.log(o.x);  // 1

回答1:


In sloppy mode, yes, it'll just be ignored - the value "assigned" will be discarded. But in strict mode (which is recommended), the following error will be thrown:

Uncaught TypeError: Cannot set property x of #<Object> which has only a getter

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

console.log(o.x);  // 1
o.x = 2


来源:https://stackoverflow.com/questions/53579207/in-javascript-what-happens-if-i-assign-to-an-object-property-that-has-a-getter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!