为什么逗号运算符会在函数调用中更改`this` [英] Why comma operator changes `this` in function call

查看:55
本文介绍了为什么逗号运算符会在函数调用中更改`this`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对话很便宜;给我看代码.

Talk is cheap; show me the code.

// equals to this.test = "inside window"
var test = "inside window";

function f () {
  console.log(this.test)
};

var a = {
  test: "inside object",
  fn: f
};

a.fn(); // "inside object"   --> fine
(a).fn(); // "inside object"   --> fine
(1, a).fn(); // "inside object"   --> fine
(a.fn)(); // "inside object"   --> fine
(1, a.fn)(); // "inside window"   --> why?

// reference equality check
console.log(
  f === a.fn && 
  (a.fn) === f && 
  f === (1, a.fn)
); // all equal :/

我已经读过ydkjs书,并且我熟悉调用站点和动态 this 绑定,但是我不明白为什么最后一个函数调用将 window 作为其上下文;在这个对照实验中,只有一件事更改为()逗号运算符,正如您在最后一条语句中看到的那样,逗号运算符做的事情很奇怪.我怀疑它在返回值时会进行赋值(因为如果进行赋值,则会发生相同的结果),但是我不确定.

I had read ydkjs book and Im familiar with call-site and dynamic this binding, but I don't understand why the last function call has window as its this context; in this controlled experiment that only thing that is changed () and comma operator and as you can see in the last statement comma operator is doing something weird. I suspect it does an assignment when it returns the value (since if we do an assignment the same result happens) but I'm not sure.

推荐答案

给出:

foo.bar()

bar 内部,将为 foo .

(有一些例外,例如使用箭头功能定义了 bar 时,但在这种情况下不适用).

(There are exceptions, such as when bar is defined with an arrow function, but they don't apply in this case).

给出:

const bar = foo.bar;
bar();

现在已在没有 foo 上下文的情况下调用了该函数,因此 this 现在是默认对象(在浏览器中为 window )

Now the function has been called without the context of foo so this is now the default object (which is window in a browser).

表达式:(1,foo.bar)计算为右侧.这就是功能.

The expression: (1, foo.bar) evaluates as the right-hand side. This is the function.

就像您已将其复制到变量一样,这会在调用函数之前将函数与对象断开连接,因此您将获得相同的效果.

Just as if you had copied it to a variable, this disconnects the function from the object before you call it, so you get the same effect.

没有分配,因为您没有涉及变量,但是您正在调用表达式的结果,而不是直接调用对象方法.

There's no assignment because you haven't involved a variable, but you are calling the result of an expression and not the object method directly.

这篇关于为什么逗号运算符会在函数调用中更改`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆