这个问题在这里已经有了答案:
Does the comma operator influence the execution context in Javascript?
(2 个回答)
2年前关闭。
给定以下代码,为什么 (obj.foo)()
接收 window
作为this
?在我看来,括号被忽略了,而不是被视为计算结果为 foo
的表达式。 ?
window.bar = 'window';
const obj = { bar: 'obj' };
obj.foo = function() {
console.log(`Called through ${this.bar}`);
}
obj.foo(); // Called through obj
(obj.foo)(); // Called through obj - Why?
(0, obj.foo)(); // Called through window
(true && obj.foo)(); // Called through window
最佳答案
它们没有被忽略,而是 (obj.foo)
的结果是一样的Reference (规范术语)作为 obj.foo
的结果(参见规范中的 this section)。所以property accessor具有相同的信息可用于获取对象和属性并将该对象用作 this
.
关于javascript - 如果括号仅包含属性访问器,是否会忽略括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58970178/