【问题标题】:ES6 Classes: Bind "this" to nested functionsES6 类:将“this”绑定到嵌套函数
【发布时间】:2020-08-14 18:28:05
【问题描述】:

我在一个 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();

【问题讨论】:

    标签: javascript class ecmascript-6 this


    【解决方案1】:

    您可以使用箭头函数。它们以相当相似的方式工作。 箭头符号将 this 替换为箭头函数作用域的上下文值。

    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();

    【讨论】:

    • 确实如此。箭头函数是解决这个问题的完美解决方案。如果您将用户的代码包含在必要的修改中,您可能会获得更多的选票。
    • 哦,谢谢。我想如果他查找箭头功能并自己尝试。下次我会牢记这一点。
    • 感谢@Innomight!我将代码添加到您的答案中。希望我理解正确。
    【解决方案2】:

    声明一个将在子函数范围内的局部变量,并使用它代替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();

    【讨论】:

    • 在 ES5 中,是的。但在使用 ES6 类时则不然。
    • @Bergi 这是对我阅读之前已删除的评论的回复吗?如果是对我的回答的评论,我不明白。
    • 这是关于答案的(也许这是 trincot 对另一个答案的评论的延续)。我认为不应该在 ES6 中使用这种相当过时的方法,因为它可以使用箭头函数。在 ES5 中声明 self 变量是可以的。
    • @Bergi 我从来没有习惯于通过赋值而不是function 声明来定义函数。我不喜欢他们没有被吊起,所以秩序很重要。我打算添加一个箭头函数替代方案,但 innomight 已经发布了他的答案。
    • 所以我主要将箭头函数用于匿名回调,很少用于命名函数。
    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多