简体   繁体   English

setTimeout 中的箭头函数不会将窗口设置为这样

[英]Arrow function in setTimeout doesn't set window as this

I have some method of an object assigned by a decorator (that's where the function f, and ms are taken from).我有一些装饰器分配的对象的方法(这是函数 f 和 ms 的来源)。

  function() {
        setTimeout(() => f.apply(this, arguments), ms); 
      };

'this' refers here to the object. “this”在这里指的是对象。 But 'this' of setTimeout is window, not that object.但是 setTimeout 的 'this' 是窗口,而不是那个对象。 If 'this' of an arrow function is taken lexically, then how come it's not taken from setTimeout?如果箭头函数的“this”是词法上的,那么它为什么不是从 setTimeout 中取得的? After all, in the following code:毕竟,在以下代码中:

let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};

user.sayHi(); // Ilya

'this' is taken from the function above. 'this' 取自上面的函数。 So if that function is setTimeout in the first situation why aren't both situations the same?因此,如果该函数在第一种情况下是 setTimeout 为什么两种情况不一样? I thought it might have had something to do with the function being passed as argument in one case, and in the other one as a local variable, but wouldn't this come down to the same in lexical environments?我认为这可能与在一种情况下作为参数传递的函数有关,而在另一种情况下作为局部变量传递,但这在词法环境中不会归结为相同吗?

Why is there a difference?为什么有区别?

Besides, to test this out:此外,要测试一下:

let obj = {name : "Jeff"};
let obj2 = {name : "Bart", fun2 : function(fun){fun();}};

obj.name2 = obj2.fun2(() => alert(this.name));

but now I don't get "Bart" alerted, but an empty string.但现在我没有收到“Bart”警报,而是一个空字符串。 When I replace "name" with length, I just get 0, the 'this' refers to the window.当我用长度替换“名称”时,我只得到 0,“this”指的是窗口。

Why doesn't this work as intended?为什么这不能按预期工作?

If 'this' of an arrow function is taken lexically, then how come it's not taken from setTimeout?如果箭头函数的“this”是词法上的,那么它为什么不是从 setTimeout 中取得的?

Lexical means that the scope is taken from where the function is declared, not where it is passed to.词法意味着作用域取自函数声明的位置,而不是传递到的位置。

Inside a function, the value of this depends on how the function is called.在函数内部, this 的值取决于函数的调用方式。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

function f1() {
  return this;
}

// In a browser:
f1() === window; // true

In your function you have passed the window object to the setTimeout.在您的函数中,您已将window对象传递给 setTimeout。

If you alter you function and pass just arguments you will get the object:如果您更改函数并仅传递参数,您将获得对象:

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

function a (){
  setTimeout(() => f.apply([1]), 1000); // here this = [1]
}

a();  // Array [1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM