Function binding

  • setTimeout is a window object method so ‘this’ will always refer to window by default.  (#2)
  • To override ‘this’ default binding, pass in an anonymous function (#1) or use .bind (#5) or .call (.call will invoke the function immediately).
  • setTimeout will automatically invoke the passed in function after wait time.
    • If you want to call the function immediately, use .call (#3) or invoke the function when you pass it in as argument (#4).
  • Good refresher on the differences between call, bind, and apply.
    • Call invokes the function and allows you to pass in arguments one by one.
    • Apply invokes the function and allows you to pass in arguments as an array.
    • Bind returns a new function, allowing you to pass in a this array and any number of arguments.
var name = "Window";
var alice = {
  name: "Alice",
  sayHi: function() {
    alert(this.name + " says hi");
  }
};
var bob = { name: "Bob" };
setTimeout(function() {
  alice.sayHi();
}, 1000);
// #1. alice says hi, after 1 second. 

setTimeout(alice.sayHi, 1000); 
// #2. window says hi, after 1 second.

setTimeout(alice.sayHi(), 1000); 
// #3. window says hi, immediately.

setTimeout(alice.sayHi.call(bob), 1000);
// #4. bob says hi, immediately

setTimeout(alice.sayHi.bind(bob), 1000);
// #5. bob says hi, after 1 second.

Note to self:

When you bind outside setTimeout, you have to save it to a variable in order to keep it bound.  Below is an example of a failed binding of the sayHi function to bob:

var name = "Window";
var alice = {
  name: "Alice",
  sayHi: function() {
    alert(this.name + " says hi");
  }
};
var bob = { name: "Bob" };


alice.sayHi.bind(bob); // this needs to be saved!!

setTimeout(alice.sayHi(), 1000);
// alice says hi, immediately.
Advertisements
Function binding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s