Sanjay Idpuganti
Sanjay Idpuganti

Reputation: 320

Bind on method inside object. Gives unexpected results

I was trying to call bind inside a JavaScript object in node.js like so.

var obj = {
  m: function () {
    console.log(this)
  }.bind(obj),
}

When I call obj.m(), I was expecting this inside function m to be obj. But the global object is getting printed.

Can anyone explain why this happens.

Upvotes: 0

Views: 51

Answers (1)

Quentin
Quentin

Reputation: 944010

The object literal has to be completely evaluated before it is assigned to obj.

At the time you call bind(obj), the value of obj is still undefined.

Hence, the global object is bound.

Upvotes: 1

Related Questions