2

I'm binding the function foo to the object myObject. I'm expecting the call to foo before I bind to log global to the console, and after the bind to log myObject to the console.

var name = 'global';

function foo() {
  console.log(this.name);
}

var myObject = {
  name: 'myObject'
};

foo();
foo.bind(myObject);
foo();

The output is the global message in both instances though.

BanksySan
  • 27,362
  • 33
  • 117
  • 216

1 Answers1

3

foo.bind() returns a new function that has the binding, it doesn't modify the original function.

var name = 'global';

function foo() {
  console.log(this.name);
}

var myObject = {
  name: 'myObject'
};

foo();
bar = foo.bind(myObject);
bar();
Barmar
  • 741,623
  • 53
  • 500
  • 612