在 JavaScript 中,如果我分配给具有 getter 但没有 setter 的对象 属性 会发生什么情况?
In JavaScript, what happens if I assign to an object property that has a getter but no setter?
在下面的代码中,都使用了console.log(o.x)
打印1
。分配 o.x = 2
会发生什么?只是被忽略了吗?
var o = {
get x() {
return 1;
}
}
console.log(o.x); // 1
o.x = 2
console.log(o.x); // 1
在草率模式下,是的,它会被忽略 - 值 "assigned" 将被丢弃。但是在严格模式下(推荐),会抛出如下错误:
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
在下面的代码中,都使用了console.log(o.x)
打印1
。分配 o.x = 2
会发生什么?只是被忽略了吗?
var o = {
get x() {
return 1;
}
}
console.log(o.x); // 1
o.x = 2
console.log(o.x); // 1
在草率模式下,是的,它会被忽略 - 值 "assigned" 将被丢弃。但是在严格模式下(推荐),会抛出如下错误:
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