javascript - 如何将使用 "this"关键字的函数传递到 JavaScript 类中?

标签 javascript class

我有课

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

当我使用 new MenuItem("MyMenuItem", (event) => { console.log(this.title); }); 调用构造函数时关键字this指的是我在其中创建 MenuItem 的范围。

有没有办法使用 this.title在我传递给构造函数的函数中?

最佳答案

不带箭头功能。箭头函数没有自己的上下文(又名 this),因此您需要一个常规的上下文:

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

关于javascript - 如何将使用 "this"关键字的函数传递到 JavaScript 类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46833377/

相关文章:

Java:为类的所有实例设置 boolean 值

javascript - 我可以在 ScriptBundle 中包含的 Javascript 中使用 Razor 语法吗?

javascript - 如何调试 JQuery 选项卡的浏览器兼容性问题?

java - 有没有更好的方法来通过对对象数组执行碰撞检测?

C++ 重载指针 ostream

c++ - 在整个项目中使用在不同文件中声明的对象

javascript - 如何使用位于 contentplaceholder 中的 asp.net 复选框控件的 javascript 函数?

javascript - 隐藏 <input type ="date"ng-model ="jobDueDate"> 到 unix 时间戳

javascript - JS : Check Query String for GET variables that are not in an array?

python - 如何覆盖父类中的字段