我有课
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/