Osama Xäwãñz Osama Xäwãñz - 1 month ago 19
Javascript Question

what does bind(this) means?

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
in
bind
really means.

Below is the code from my react app with firebase Database.

componentWillMount: function() {
this.firebaseRef = firebase.database().ref('todos');
this.firebaseRef.limitToLast(25).on('value', function(dataSnapshot) {
var items = [];
dataSnapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item['key'] = childSnapshot.key;
items.push(item);
}.bind(this));

this.setState({
todos: items
});
}.bind(this));

},

Answer

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().

Comments