class Test {
DISPATCH_TABLE = {
"Outer Method": this.outerMethod
}
innerMethod() {
console.log("success");
}
outerMethod() {
console.log(this);
this.innerMethod();
}
dispatch(method_name) {
this.DISPATCH_TABLE[method_name]()
}
constructor() {
this.outerMethod = this.outerMethod.bind(this)
}
}
t = new Test()
t.dispatch("Outer Method")
这将记录调度表本身,然后显示错误“ this.innerMethod不是函数”。我知道为什么 this 会绑定到调度表而没有构造函数中的bind()调用,但是我认为包括该调用应该强制 this 可以在对绑定方法的任何调用中引用该类。
我没有怪我的期望是JavaScript或bind()。我只是不知道为什么我的期望是错误的。
我可以只使用switch语句代替调度表,但是如果可以的话,我更愿意使用调度表。
答案 0 :(得分:2)
使用箭头功能可能会更好,这些功能总是正确的。
我也自由更改了分配表,以将函数的“详细名称”映射到内部方法名称。
class Test {
DISPATCH_TABLE = {
"Outer Method": "outerMethod",
};
innerMethod = () => {
console.log("success");
};
outerMethod = () => {
console.log(this);
this.innerMethod();
};
dispatch(method_name) {
const meth = this[this.DISPATCH_TABLE[method_name]];
if (!meth) throw new Error(`no such method ${meth}`);
return meth();
}
}
t = new Test();
t.dispatch("Outer Method");