Skip to content

Instantly share code, notes, and snippets.

@jaredwilli
Forked from icodejs/CallApply.js
Created October 20, 2013 18:37
Show Gist options
  • Save jaredwilli/7073490 to your computer and use it in GitHub Desktop.
Save jaredwilli/7073490 to your computer and use it in GitHub Desktop.
// Invoking a function and applying it have the same
// result. apply() takes two parameters: the first one is an object to bind to this inside of
// the function, the second is an array or arguments, which then becomes the array-like
// arguments object available inside the function. If the first parameter is null, then this
// points to the global object, which is exactly what happens when you call a function
// that is not a method of a specific object.
// When a function is a method of an object, there’s no null reference passed around. Here the
// object becomes the first argument to apply():
// In addition to apply(), there’s a call() method of the Function.prototype
// object, but it’s still just syntax sugar on top of apply(). Sometimes it’s better to use the
// sugar: When you have a function that takes only one parameter, you can save the work
// of creating arrays with just one element:
// the second is more efficient, saves an array
sayHi.apply(alien, ["humans"]); // "Hello, humans!"
sayHi.call(alien, "humans"); // "Hello, humans!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment