我如何(或有可能)创建一个 JavaScript 基类,在其构造函数期间自动调用其每个实例方法的 bind?
我试过了,没有成功:
class BaseClass {
constructor() {
// for (let i in this.__proto__) { // <-- this also failed
for (let i in this) {
if (typeof this[i] === 'function') {
this[i] = this[i].bind(this);
}
}
}
}
class MyClass extends BaseClass {
constructor() {
super();
this.foo = 'bar';
}
myMethod() {
console.log(this.foo);
}
}
当我在构造函数中设置断点时,this.myMethod
存在,this.__proto__
中存在,Object中不存在.getOwnPropertyNames(this)
既不在类的构造函数中,也不在基类的构造函数中。
基本上我正在尝试执行this blog post 中的奖励步骤 (结论后)无需手动定义或调用_bind()
。
最佳答案
ES6 类方法是不可枚举的,所以你必须自己遍历原型(prototype)链。
for (let obj = this; obj; obj = Object.getPrototypeOf(obj)){
for (let name of Object.getOwnPropertyNames(obj)){
if (typeof this[name] === 'function'){
this[name] = this[name].bind(this);
}
}
}
避免这种复杂性是“奖励步骤”明确命名要绑定(bind)的事物的原因。在创建每个对象时执行此操作也会慢得多。
关于javascript - 在构造函数期间自动调用 es6 中所有实例方法的 bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30649398/