javascript - 在构造函数期间自动调用 es6 中所有实例方法的 bind()

标签 javascript ecmascript-6

我如何(或有可能)创建一个 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/

相关文章:

javascript - 是否可以在 underscore.js 或 lodash 模板中添加非 html 注释?

javascript - 为什么我在这个简单的组件中遇到 Angular 编译错误

javascript - 无法在 Jquery 中执行 show() 方法

javascript - 除了使用 jquery 悬停的内容之外,如何淡化整个 html 正文内容?

javascript - 实例化每个键都等于 null 的对象的最佳方法?

javascript - 是否可以将 instanceof 运算符结果作为值获取?

javascript - this 在 render() 中的一个函数中

javascript - 对象字面量中的箭头函数

javascript - 通过javascript调用MVC操作方法但不使用AJAX

javascript - 动态表格单元格 ID 和名称在 IE 浏览器的 Jquery 中不可更新