2

我的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在这个示例中访问?

提前致谢!

4

3 回答 3

4

你必须要.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 指出的那样,与文件访问相比,它肯定不会成为您的瓶颈。

于 2013-07-08T14:50:21.717 回答
3
MyClass.prototype.myFunction = function(file){
  var that = this;
  // some lines of code later...
       console.log(that.someValue);
}
于 2013-07-08T14:48:44.967 回答
2

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 */
  }
}

同时查看这个精彩的主题:“this”关键字是如何工作的?

于 2013-07-08T14:50:59.780 回答