在es6的构造过程中对所有实例方法自动调用bind()

Automatically call bind() on all instance methods in es6 during constructor

本文关键字:实例方法 调用 bind es6 过程中      更新时间:2023-09-26

我怎么能(或它是可能的)使一个JavaScript基类,自动调用绑定它的每个实例方法在它的构造函数?

I tried, without success:

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)中,无论是在类的构造函数中还是在基类的构造函数中都不存在。

基本上我试图做奖金步骤在这篇博客文章中(在结论之后)不需要手动定义或调用_bind()

ES6类方法是不可枚举的,所以你必须自己遍历原型链。

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

避免这种复杂性是"奖励步骤"明确命名要绑定的东西的原因。对于每一个单独的对象创建它也会慢很多