ES2015 classes "not autobind"?

I’ve been using React for a while, and I’m comfortable with the concept that I have to manually bind the methods of my component to the component instance, since React decided to be "idiomatic" in non-automatic mode:

Therefore, we decided not to have this model built into the React class. You can still explicitly use prebind methods in your constructor if you want.

class Counter extends React.Component {
  constructor() {
    super();
    this.tick = this.tick.bind(this);
  }
  tick() {
    ...
  }
  ...
}

- https://facebook.imtqy.com/react/blog/2015/01/27/react-v0.13.0-beta-1.html

We can clearly see the effects of this in this example http://jsbin.com/citafaradu/2/edit?js,console,output , from this similar question: How to properly bind the current object context in ES6 using babelify

- , , , ES2015. "!" , , , ... , JS! , , , ?

- , "" es6, , , - React, :

ES6 . : https://facebook.imtqy.com/react/docs/reusable-components.html#no-autobinding

, javascript ES6 [ ]. React , JavaScript. ES5 , React . ES6 JavaScript.
- "cody", https://github.com/facebook/react/issues/4065

. , JSX? :

{
    key: "render",
    value: function render() {
      return React.createElement("div",null,
        React.createElement("input", { 
          type: "text", onChange: this.handleBindedChange 
        }),
        React.createElement("br", null),
        React.createElement("input", { 
          type: "text", onChange: this.handleUnbindedChange 
        }),
        React.createElement("br", null),
        React.createElement("p",null,"Result: ",this.state.demo)
     );
    }
 }

. babel Object.defineProperty, , , , .

, . , , , es2015, , , React? , - ? - , ? , , ES2015? , , ?

+4
3
+3

, React , , React.createClass . .

, , JavaScript, this "" . ES6, .

, ES6 + . :

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
Hide result

. , Python , .

+5

, ES6 ​​:

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();
Hide result
+1

Source: https://habr.com/ru/post/1659236/


All Articles