javascript - es6 Javascript 类在回调中使用 this

标签 javascript node.js ecmascript-6

新的 es6 类允许您在方法中使用自引用变量 this
但是,如果类方法具有子函数或回调,则该函数/回调不再有权访问自引用变量 this

class ClassName {
  constructor(dir){
    this.dir = dir;
    fs.access(this.dir, fs.F_OK | fs.W_OK, this.canReadDir);//nodejs fs.access with callback
  }

  canReadDir(err){
    this.dir;// NO ACCESS to class reference of this
  }
  //OR
  aMethod(){
    function aFunc(){
      this.dir;// NO ACCESS to class reference of this
    }
  }
}

有什么解决办法吗?

最佳答案

您有以下选择:

1) 使用箭头函数:

class ClassName {
  // ...
  aMethod(){
    let aFun = () => {
      this.dir;// ACCESS to class reference of this
    }
  }
}

2) 或者 bind() 方法:

class ClassName {
  // ...
  aMethod(){
    var aFun = function() {
      this.dir;// ACCESS to class reference of this
    }.bind(this);
  }
}

3) 将 this 存储在专用变量中:

class ClassName {
  // ...
  aMethod(){
    var self = this;
    function aFun() {
      self.dir;// ACCESS to class reference of this
    }
  }
}

This article描述了 JavaScript 中关于 this 和箭头函数的必要细节。

关于javascript - es6 Javascript 类在回调中使用 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36498029/

相关文章:

javascript - 如何使用 css、html 和 jquery 创建标记样式?

javascript - 用连字符和/或撇号匹配单词的正则表达式

node.js - 在集合 "library"中找不到原理图 "@schematics/angular"

javascript - ES6 箭头函数

javascript - Switch 中的 ES6 模式匹配

javascript - 没有访问控制允许带有 java rest 后端的原始 ionic 项目

javascript - 带有查询字符串的 URL 的正则表达式

javascript - 从 Node.js 模块访问全局变量?

html - NodeJS 提交的数据在 Mysql 数据库中未定义

javascript - “箭头功能”和“功能”是否等效/可互换?