Do ES2015 Classes “not autobind”?

前端 未结 5 1054
说谎
说谎 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:35

    Auto Binding.

    This library is working fine for me in Node.js. But I haven't sure about this will work too for React.js.

    const AUTO_BIND = require("auto-bind");
    
    class Programmer {
    
      constructor(name, age) {
        this.Name = name;
        this.Age = age;
        AUTO_BIND(this);
        //* For React component
        //* AUTO_BIND.react(this);
      }
    
      ShowName() {
        console.log(`My name is ${this.Name}`);
      }
    
      ShowAge() {
        console.log(`My age is ${this.Age}`);
      }
    
      ShowDetail() {
        this.ShowName();
        this.ShowAge();
      }
    }
    const programmer = new Programmer("M. Hamza Rajput", 25);
    
    const { ShowDetail } = programmer;
    
    ShowDetail();
    
    console.log(programmer.hasOwnProperty('ShowDetail')); // true
    console.log(typeof programmer === 'object'); // true
    console.log(Programmer.prototype.hasOwnProperty('ShowDetail')); // true
    

提交回复
热议问题