为什么JavaScript的bind()不能按我期望的那样在这里工作?

问题描述 投票:0回答:1
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将绑定到调度表without的构造函数中的bind()调用,但是我认为包括该调用应该强制this引用该类。在对绑定方法的任何调用中。

我并没有怪我的期望是JavaScript或bind()。我只是不知道为什么我的期望是错误的。

我可以只使用switch语句而不是调度表,但如果可以的话,我宁愿使用调度表。

javascript this bind
1个回答
1
投票

使用箭头功能可能会更好,这些功能总是正确的。

我也自由更改了调度表,以将函数的“详细名称”映射到内部方法名称。

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");
© www.soinside.com 2019 - 2024. All rights reserved.