为什么 JavaScript 的 bind() 在这里没有像我预期的那样工作?
Why is JavaScript's bind() not working here as I expect it?
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")
这会记录调度 table 本身,然后打印错误 "this.innerMethod is not a function"。我理解为什么 this 会绑定到调度 table 而没有 构造函数中的 bind() 调用,但我认为包括该调用应该强制 this 在对绑定方法的任何调用中引用 class。
我并不是因为我的期望而责怪 JavaScript 或 bind()。只是不知道为什么我的期望是错误的。
我可以只使用 switch 语句而不是调度 table,但如果可以的话我更愿意使用调度 table。
您可能会更喜欢使用箭头函数,它总是正确地绑定到 this。
我冒昧地更改了您的分派 table 以将函数 "verbose names" 映射到内部方法名称。
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");
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")
这会记录调度 table 本身,然后打印错误 "this.innerMethod is not a function"。我理解为什么 this 会绑定到调度 table 而没有 构造函数中的 bind() 调用,但我认为包括该调用应该强制 this 在对绑定方法的任何调用中引用 class。
我并不是因为我的期望而责怪 JavaScript 或 bind()。只是不知道为什么我的期望是错误的。
我可以只使用 switch 语句而不是调度 table,但如果可以的话我更愿意使用调度 table。
您可能会更喜欢使用箭头函数,它总是正确地绑定到 this。
我冒昧地更改了您的分派 table 以将函数 "verbose names" 映射到内部方法名称。
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");