使用 () 强制 JavaScript 解释器先求值

using () for forcing JavaScript interpreter to evaluate first

我正在学习Js。在阅读 YDKJS 系列时,我通过一个例子来努力弄清楚发生了什么。

function foo() {
  console.log(this.a);
}

var a = 90;

var obj1 = {
  a: 1,
  foo: foo
};

var obj2 = {
  a: 2
};

(obj2.foo = obj1.foo)(); //90
obj2.foo(); //2

在这段代码中,为什么 (obj2.foo = obj1.foo)(); foo 的 this 变量指向全局对象,在下一行中,它指向 obj2,即调用函数的上下文。你能告诉我,我在这里缺少什么吗? obj2.foo = obj1.foo 中 () 的正确作用是什么? IIFE 中使用了相同的语法。有人可以解释一下吗?

语法不一样。 JavaScript不区分方法和函数作为值,区别纯粹在于方法调用。语法 receiver.method(...args) (如果 receiver.method 是非箭头函数)调用 as 方法,即它会在调用期间将 this 设置为 receiver。 (等效地,语法 receiver[methodname](...args) 将执行相同的操作。)

任何其他函数调用语法都只是函数调用,不会影响this。具体来说,(obj2.foo = obj1.foo) 只计算一个函数,它不知道应该寻址到哪个接收器,因此 this 是全局对象,this.a 是全局变量 a.

编辑:示例...

window.context = "global";
let foo = {
  context: "foo",
  fn: function() { console.log(this.context); },
  arrow: () => { console.log(this.context); },
}

console.log(this.context); // global object (`window` in browser, `global` in Node)
foo.fn(); // method call syntax; `this` is set to `foo`
foo["fn"](); // equivalent to the above; `this` is set to `foo`
foo.arrow(); // method call syntax but arrow, so doesn't matter; `this` is unchanged
let fnS;
fnS = foo.fn; fnS(); // no receiver, regular function call, `this` is unchanged
(fnS = foo.fn)() // equivalent to the previous one

在这些示例中,只有 foo.fn()foo["fn"]() 会将 this 设置为 foo;所有其他人将保持原样(即 this 将成为全局对象)。