在JavaScript中,如果我分配给具有getter但没有setter的对象属性,会发生什么情况? [英] In JavaScript, what happens if I assign to an object property that has a getter but no setter?
本文介绍了在JavaScript中,如果我分配给具有getter但没有setter的对象属性,会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,同时使用console.log(o.x)
和1
.作业o.x = 2
会发生什么?只是被忽略了吗?
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
推荐答案
在草率模式下,是的,它将被忽略-值"assigned"将被丢弃.但是在严格模式(建议使用)下,将引发以下错误:
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:
未捕获的TypeError:无法设置仅有吸气剂的
#<Object>
的属性x
'use strict';
var o = {
get x() {
return 1;
}
}
console.log(o.x); // 1
o.x = 2
这篇关于在JavaScript中,如果我分配给具有getter但没有setter的对象属性,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文