回调函数中的变量作用域

Variable scope in callback function

本文关键字:变量 作用域 函数 回调      更新时间:2023-09-26

我的javascript代码遇到了问题。

我有一个类MyClass,并将函数myFunction添加到它的原型中。

MyClass.prototype.myFunction = function(file){
    if(some condition){
       fs.exists("./" + file, function(exists){
           if(exists)
               console.log(this.someValue);
               /* lot of other code */
           else
               /* do something else */
    });
    }else{
        /* do something */
    }
}

我的问题是this.someValue的范围(例如,我只想打印它)。每当exists等于true时,控制台就会记录undefined,但事实并非如此。如果我要在fs.exists()之外打印它,那么它有一个值,所以我想这是一个范围问题。

如何访问此示例中的this.someValue

提前感谢!

您必须.bind您的内部函数

MyClass.prototype.myFunction = function(file){
    if(some condition){
       fs.exists("./" + file, function(exists){
           if(exists)
               console.log(this.someValue);
               /* lot of other code */
           else
               /* do something else */
    }.bind(this));
    }else{
        /* do something */
    }
}

这可以重写为更干净的

MyClass.prototype.myFunction = function myFunction(file){
  if(some condition){
    fs.exists("./" + file, this.doSomething.bind(this));
  }
  else{
    // do something else
  }
}
MyClass.prototype.doSomething = function doSomething(exists) {
  if(exists) {
    console.log(this.someValue);
    // lot of other code
  }
  else {
    // do something else
  }
}

我个人喜欢这个解决方案,因为它可以让你保持出色的代码组合,并防止你嵌套function(){ function(){ function(){ ... }}}。它还可以防止一堆var that = this;var self = this;变量四处浮动,让您怀疑哪个范围是哪个范围。

是的,.bind速度较慢,但正如minitech所指出的,与文件访问相比,它肯定不会成为您的瓶颈。

MyClass.prototype.myFunction = function(file){
  var that = this;
  // some lines of code later...
       console.log(that.someValue);
}

As this-是由函数范围定义的关键字,用于响应函数的所有者或调用方。因此,您可以将其指针存储在另一个变量中:

MyClass.prototype.myFunction = function(file) {
  if(some condition) {
    var self = this; // create variable with pointer to 'this'
    fs.exists("./" + file, function(exists) {
      if(exists) {
        console.log(self.someValue); // we can access it to parent scope variables
        /* lot of other code */
      } else {
        /* do something else */
      }
    });
  } else {
    /* do something */
  }
}

我们不妨看看这个精彩的话题:;这个";关键词工作?