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
  • 25,929
  • 29
  • 105
  • 202

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
  • 669,327
  • 51
  • 454
  • 560