javascript - Javascript - 如何在 ES6 类中使用“this”
问题描述
如果我有以下方法:
element.addEventListener('click', foo)
const fooList = {
1: new barClass().function1,
2: new barClass().function2,
3: new barClass().function3,
....
}
const foo = (bar) => {
foobar = bar.innerText;
let hasFunctionInList = fooList[foobar ];
if (hasFunctionInList) fooList[foobar ]()
}
当我在课堂上时,我能做些什么不同的事情来这样称呼课堂?:
class barClass {
function1 () {}
function2 () {
** this.function1() ** // in this case "this" doesn't stands for the class barClass, and gives me an error "this.function1 is not a function"
}
function3 () {}
}
解决方案
经典方式是使用绑定:
const fooList = {};
let bar = new barClass();
let func = barClass.function1;
fooList[1] = func.bind(bar);
bar = new barClass();
func = bar.function2;
fooList[2] = func.bind(bar);
...
或者在 ES6 中使用箭头语法:
const fooList = {};
let bar = new barClass();
fooList[1] = () => barClass.function1();
bar = new barClass();
fooList[2] = () => barClass.function2();
推荐阅读
- c# - ASP.Net Core 2 中的全局变量
- asp.net-mvc - ASP.NET MVC 路由 - 添加站点名称?
- microsoft-teams - 在 Microsoft Teams 中保存连接器配置时出现空异常
- php - 在 mysqli 查询的表中显示数组结果
- conda - 无法使用 CondaVerificationError 创建新环境:ncurses 的包已损坏
- java - 物品没有按需要放置。[爪哇]
- django - Stripe Django:如何通过计划向现有客户收费
- php - 我想将 json 数据加载到 mysql 数据库,但它需要太多时间
- php - Yii2如何根据客户端的时区显示时间?
- ios - iOS 无法打开下载的 MS Word 文件