es6 Javascript类在回调中使用此方法 [英] es6 Javascript class using this inside a callback

查看:422
本文介绍了es6 Javascript类在回调中使用此方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The new es6 class allows you to use the self reference variable this inside methods.
However if a class method has a sub function or a callback, that function/callback no longer has access to the self reference variable 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
    }
  }
}

对此有什么解决办法吗?

Is there any solution to 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存储在专用变量中:

3) Store this in a specialised variable:

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

本文描述了有关this和JavaScript中的箭头功能.

This article describes the necessary details about this and arrow functions in JavaScript.

这篇关于es6 Javascript类在回调中使用此方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆