Osama Xäwãñz Osama Xäwãñz - 10 months ago 78
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

is really confusing me.What does
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;

todos: items


Answer Source

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