ES6类:将“ this”绑定到嵌套函数

问题描述

我在ES6类中有多个嵌套函数。现在,我想知道如何轻松地将类实例的 this 绑定到所有子功能。

我知道...

subfunction1.bind(this)();

...但是对于多个嵌套函数来说,这似乎是一个尴尬的解决方案。

有人知道更优雅的解决方案吗?

class User {
  constructor(name) {
    this.name = name;
  }

  mainFunction() {
    console.log(this.name);//"Paul"
    
    //In order for the nested functions to get "this" it is needed to bind it 
    //to the subfunction as shown below. Is there an easier way to achieve
    //this for all the subfunctions at once?
    
    subfunction1.bind(this)();
    subfunction2.bind(this)();
    
    function subfunction1() {
      console.log(this.name);//"Paul"
    }
    
    function subfunction2() {
      console.log(this.name);//"Paul"
    }
  }
}
const paul = new User("Paul");
paul.mainFunction();

解决方法

您可以使用箭头功能。它们以类似的方式工作。 箭头符号会将其替换为箭头函数作用域的上下文值。

class User {
  constructor(name) {
    this.name = name;
  }

  getSummary() {
    console.log(this.name);
    const subfunction1 = () => {
      console.log(this.name);//"Paul"
    }
    const subfunction2 = () => {
      console.log(this.name);//"Paul"
    }
    subfunction1();
    subfunction2();
  }
}
const paul = new User("Paul");
paul.getSummary();

,

声明一个将在子函数范围内的局部变量,并使用它代替this

class User {
  constructor(name) {
    this.name = name;
  }

  mainFunction() {
    const self = this;
    console.log(this.name);//"Paul"
       
    subfunction1();
    subfunction2();
    
    function subfunction1() {
      console.log(self.name);//"Paul"
    }
    
    function subfunction2() {
      console.log(self.name);//"Paul"
    }
  }
}
const paul = new User("Paul");
paul.mainFunction();

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...