哪些变量在匿名函数中可用

Which variables are available inside an anonymous function?

本文关键字:函数 变量      更新时间:2024-03-16

关于scope,我一直感到困惑:

this.init = function(){
  var t = this;
  setTimeout(function(){
    // why is t still available here?
    t.initgame();
    // but not this?
    this.initgame();
  }, 500);
}
this.initgame = function() {
  // yada yada
}

在一个匿名函数内部,作用域与外部不同。但是,在上面的例子中,为什么变量"t"在超时函数中可用,而"this"不起作用呢?

问题是以window作为作用域调用setTimeout

使用专用变量来存储thist)是一种非常有效且常见的解决方案。

在现代浏览器上,bind有时很方便:

setTimeout((function(){
    // use this
}).bind(this), 500);

当匿名函数运行时,它不再作为init的成员函数运行,而是作为window的顶级函数运行。因此,this.initgame()没有任何意义。

例如,在超时函数内运行console.log(this)返回如下:

Window {top: Window, window: Window, location: Location, external:...

使用var t = this时,可以将引用指定给当前对象,这样可以工作。