Maxmengt
Maxmengt

Reputation: 117

How to understand "{ fun: function.bind(this) }"?

var a = 2;
var c = {
    a: 3,
    say: function() {
        console.log(this.a);
    }.bind(this);
};
c.say();
// Ouput: 2

The output is 2, and I don't know why. Why this point to global?

Upvotes: 1

Views: 75

Answers (3)

Max Koretskyi
Max Koretskyi

Reputation: 105439

When this statement is executed in global scope:

var a = 2;

it's equal to window.a = 2.

In your code the first thing that happens is the .bind(this) method is executed. Since you're in a global scope, this here points to window. So, the say function is bound to the window and this.a inside this function sort of becomes window.a and accordingly this console.log(this.a) becomes console.log(window.a).

In order to understand the behavior, you have to first understand what bind does. Check this documentation. Check this, for example:

var a = 2;
var c = {
    a: 3,
    say: function() {
        console.log(this.a);
    }.bind({a: 7});
};
c.say(); // outputs 7

Upvotes: 3

Rajesh
Rajesh

Reputation: 24915

Default value for this is window. Also since your code is not wrapped in a function, var a becomes a part of window

Try wrapping it inside an IIFE

(function() {
  var a = 2;
  var c = {
    a: 3,
    say: function() {
      console.log(this.a);
    }.bind(this)
  };
  c.say();
})()

Upvotes: 0

KoalaGangsta
KoalaGangsta

Reputation: 556

As you're in an anonymous function you're not calling out of c. Use c.a instead.

Upvotes: 0

Related Questions