Do ES2015 Classes “not autobind”?

前端 未结 5 1057
说谎
说谎 2021-02-09 04:58

I have been using React for a while now, and I have become comfortable with the concept that I must manually bind my component methods to my component instance, as React made th

5条回答
  •  情书的邮戳
    2021-02-09 05:48

    You can make you ES6 class methods auto-bind with a little boiler-plate in the constructor:

    function autobind() {
      for (let prop of Object.getOwnPropertyNames(Object.getPrototypeOf(this))) {
        if (prop === 'constructor' || typeof this[prop] !== 'function') continue;
        this[prop] = this[prop].bind(this);
      }
    }
    
    class Test {
      constructor() {
        autobind.call(this);
        this.message = 'hello all!';
      }
      method1(){ return this.method2(); }
      method2(){ console.log(this.message);}
    }
    let test = new Test();
    let b = test.method1;
    b();

    UPDATE:

    I have since found a Babel Plugin that translates the upcomping ES Class Fields & Static Properties which you can use for functions that need to be bound to the this

    class Bork {
        //Property initializer syntax
        instanceProperty = "bork";
        boundFunction = () => {
          return this.instanceProperty;
        }
    
        //Static class properties
        static staticProperty = "babelIsCool";
        static staticFunction = function() {
          return Bork.staticProperty;
        }
    }
    
    let myBork = new Bork;
    
    //Property initializers are not on the prototype.
    console.log(myBork.__proto__.boundFunction); // > undefined
    
    //Bound functions are bound to the class instance.
    console.log(myBork.boundFunction.call(undefined)); // > "bork"
    
    //Static function exists on the class.
    console.log(Bork.staticFunction()); // > "babelIsCool"

提交回复
热议问题