首页 > 解决方案 > 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 () {}
}

标签: javascriptecmascript-6

解决方案


经典方式是使用绑定:

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();

推荐阅读