javascript - 回调函数中的变量范围

标签 javascript node.js scope

我的 javascript 代码遇到了问题。

我有一个类 MyClass 并在其原型(prototype)中添加了函数 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 指出的那样,与文件访问相比,它肯定不会成为您的瓶颈。

关于javascript - 回调函数中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17529563/

相关文章:

node.js - 这是在 mongodb 中插入和更新对象数组的安全方法吗?

r - 了解 R 中的变量作用域

javascript - 在 JavaScript 中,在函数作用域之外访问未声明的变量赋值?

javascript - AngularJS 表单输入名称验证在 ngrepeat 中不起作用

javascript - 如何将新的 HTML 添加到动态创建的弹出窗口 (Bootstrap 3)

javascript - 如何从本地服务器本身为 Google Charts 提供所有依赖项

javascript - 使用 Angular 登录谷歌

javascript - 寻找富有的状态 :collapsiblePanel on change event

javascript - Model.function 不是路由器内的函数

php - 嵌套的 foreach 范围中的 bool 值给出了意外的值