JavaScript中函数被传递时未设置”this”。

huangapple go评论70阅读模式
英文:

Javascript "this" not set in function that was passed around

问题

以下是您要翻译的内容:

我有一个类,在其中有一个方法,该方法创建一个要由某些第三方库调用的函数。在函数内部,我想调用类成员,但在函数被调用的时候,“this”关键字不再设置。如何在函数内部使“this”关键字起作用?

我有一个过于简化的示例:

class myclass
{
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    return function(x) { this.printIt(x); };
  }
}


(new myclass).getFunc()("test");

TypeError: Cannot read properties of undefined (reading 'printIt')

我也有一个解决方案,但我对此不太满意,并且我希望可以以更优雅的方式完成:

class myclass
{
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    let self = this;
    return function(x) { self.printIt(x); };
  }
}


(new myclass).getFunc()("test");
英文:

I have a class, in where I have a method that creates a function to be called by some third party library. Inside the function I want to call class members, but the "this" keyword is not set anymore at the moment the function is called. How can I get the this keyword to work inside the function?

I have an oversimplified example:

class myclass
{
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    return function(x) { this.printIt(x); };
  }
}


(new myclass).getFunc()("test");

> TypeError: Cannot read properties of undefined (reading 'printIt')

And I also have a solution which I am not happy with, and which I expect can be done in a more elegant way:

class myclass
{
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    let self = this;
    return function(x) { self.printIt(x); };
  }
}


(new myclass).getFunc()("test");

答案1

得分: 2

class myclass {
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    return function(x) {
      this.printIt(x);
    }.bind(this);
  }
}

(new myclass).getFunc()("test");
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

class myclass {
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    return function(x) {
      this.printIt(x);
    }.bind(this);
  }
}


(new myclass).getFunc()(&quot;test&quot;);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月5日 06:15:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75011917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定