【问题标题】:es6 Javascript class using this inside a callback [duplicate]es6 Javascript类在回调中使用它[重复]
【发布时间】:2016-07-29 14:59:16
【问题描述】:

新的 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
    }
  }
}

有什么解决办法吗?

【问题讨论】:

  • 你可以创建一个箭头函数来代替const aFunc = () => this.dir;
  • 使用Arrow functions
  • "新的 es6 类允许您在方法中使用自引用变量 this。" - 呃,不,这与 ES6 class 语法无关。 this 关键字的工作方式与在方法中一样。
  • 这不是真正的重复,因为这与 es6 类有关,而不仅仅是回调
  • 你是否使用一个类并不重要。函数就是函数,不管它是如何创建的。您接受的答案中的解决方案与他在副本中建议的解决方案完全相同。

标签: javascript node.js ecmascript-6


【解决方案1】:

在 aMethod() 中添加对 dir 的引用,然后在 aFunc 中使用它

aMethod() {
    var tempDir = this.dir;
    aFunc() {
        console.log(tempDir);
    }
}

【讨论】:

  • 使用 var self = this;var that = this; 并在以后使用它已经是一种很好理解的做法。
【解决方案2】:

您有以下选择:

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 描述了有关 this 和 JavaScript 中箭头函数的必要细节。

【讨论】:

  • self 不是保留词吗?
  • @Bálint 不。可以使用self
  • 第二个选项效果很好,使用箭头也可以
  • 如何编写 canReadDir(err) 函数(只是为了使示例完整)?
  • bind() 方法效果很好并且易于阅读 (y)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多