I already know that what bind do, it bound your given object or function to the function you want, but bind(this)
is really confusing me.What does this
bind(this)
here binds the context of your function inside forEach()
to the scope of the componentWillMount().
this
here refers to the the scope of componentWillMount()
.
With bind(this)
, this
keyword inside the inner function will refer to the outer scope.
This is essential because in this case this.setState
inside the forEach
function can be called as its scope is limited to componentWillMount()
.
According to the docs:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Check out this demo which illustrates the usage of bind(this)
.
class App extends React.Component {
constructor(){
super();
this.state = {
data: [{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
}
}
componentDidMount() {
this.state.data.forEach(function(item) {
console.log('outer scope ', this);
}.bind(this))
this.state.data.forEach(function(item) {
console.log('Inner scope ', this);
})
}
render() {
return (
Hello)
}
}
ReactDOM.render( , document.getElementById('app'));