Do ES2015 Classes “not autobind”?

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

    The reason why React keeps mentioning autobinding is because React.createClass was autobinding all methods. And that method was the only way to create components.

    People, especially those not that familiar with JavaScript, got used to passing methods to other components and this would "magically" work. This feature disappeared with using native ES6 classes, so they needed to emphasize the difference.

    But yes, ES6 classes are basically just syntactic sugar for constructor functions + prototype. The methods are not bound to the object:

    class Foo {
      bar() {}
    }
    
    const foo = new Foo();
    
    console.log(foo.hasOwnProperty('bar')); // false
    console.log(typeof Foo === 'function'); // true
    console.log(Foo.prototype.hasOwnProperty('bar')); // true

提交回复
热议问题