Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

javascript - Why is it necessary to use bind when working with ES6 and ReactJS?

Using ES5 development with ReactJS, a component can be stated as the following:

var MyComponent = React.createClass({
  alertSomething: function(event) {
    alert(event.target);
  },

  render: function() {
    return (
      <button onClick={this.alertSomething}>Click Me!</button>
    );
  }
});

ReactDOM.render(<MyComponent />);

In this example, the this references the object itself, which is the expected natural behavior.

Question

My question is:

How you use ES6 to create components?

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  alertSomething(event) {
    alert(event.target);
  }

  render() {
    return (
      <button onClick={this.alertSomething.bind(this)}>Click Me!</button>
    );
  }
}

ReactDOM.render(<MyComponent />);

Knowing that in JavaScript the this references the instantiated object itself when using the new operator, someone can tell me what is the real purpose of using bind? It is something related to the internal mechanisms of React?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var cat = {
  sound: 'Meow!',
  speak: function () { console.log(this.sound); }
};

cat.speak(); // Output: "Meow!"

var dog = {
  sound: 'Woof!'
};
dog.speak = cat.speak;

dog.speak(); // Output: "Woof!"

var speak = cat.speak;
speak(); // Output: "undefined"

speak = cat.speak.bind(dog);
speak(); // Output: "Woof!"

Explanation:

The value of "this" depends how the function is being called. When you provide this.alertSomething as your button's onClick handler, it changes how it will be called since you are providing a direct reference to that function, and it won't be called against your object instance (not sure if I'm phrasing that right).

The .bind function will return a new function where "this" is permanently set to the value passed to it.

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

It's best to do this in your component's constructor so that .bind is happening just once for each of your handlers, rather than on every render.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...