Michel Michel - 5 months ago 7
Javascript Question

What is the usage of .bind()

I'm reading this code, and I can't get my head around the

.bind()
function.

There is a function, and in that function I see this statement

this.layers.forEach(function(d){
//some logic here
}.bind(this));


Now, what is
.bind(this)
used for ie what does it mean, and what would be different when it would not be added?

The whole function is this:

get_data: function()
{
this.layers = [];

//more logic

this.layers.forEach(function(d){
//some logic here
}.bind(this));

return this.layers;

},


Reading the docs for .bind() didn't make it clear to me

Answer

this context inside Array#forEach will be window, to have context of your-own(In your example, context of get_data), use .bind over callback-function

var obj = {
  foo: function() {
    this.fName = 'NAME';
    [0, 1, 2, 3].forEach(function() {
      console.log('' + this);
      console.log('' + this.fName);
    });
  },
  bar: function() {
    this.fName = 'NAME';
    [0, 1, 2, 3].forEach(function() {
      console.log('' + this.fName);
    }.bind(this));
  }
}
obj.foo();
obj.bar();