Search code examples
javascriptexecutioncontext

bind() for binding to object


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.


Solution

  • 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();