简体   繁体   English

如何将使用“ this”关键字的函数传递给JavaScript类?

[英]How do I pass a function using “this” keyword into a JavaScript Class?

I have a class 我有一堂课

class MenuItem {
  constructor(title, onPress) {
    this.title = title;
    this.onPress = onPress;
  }
}

When I invoke the constructor using new MenuItem("MyMenuItem", (event) => { console.log(this.title); }); 当我使用new MenuItem("MyMenuItem", (event) => { console.log(this.title); });调用构造函数时new MenuItem("MyMenuItem", (event) => { console.log(this.title); }); the keyword this is referring to scope that I'm creating the MenuItem in. this是我在其中创建MenuItem的作用域的关键字。

Is there a way to use this.title in the function I'm passing to my constructor? 有没有办法在我传递给构造函数的函数中使用this.title

Not with an arrow function. 不具有箭头功能。 Arrow functions dont have their own context (aka this ) , so you need a regular one: 箭头函数没有自己的上下文(也称为this ),因此您需要一个常规的上下文:

MenuItem("MyMenuItem", function(event){ 
  console.log(this.title); 
});

这样的事情应该起作用:

this.onPress = onPress.bind(this)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM