Skip to content

Instantly share code, notes, and snippets.

@vishaltelangre
Created March 26, 2013 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishaltelangre/5245619 to your computer and use it in GitHub Desktop.
Save vishaltelangre/5245619 to your computer and use it in GitHub Desktop.
Difference between `call` and `apply` in JS
var myFunc = function(arg1, arg2) {
console.log(this, arg1, arg2); // guess what is `this` !
};
var newObject = {};
myFunc('foo', 'bar'); //outputs: Window "foo" "bar"
// .call takes unlimited number of arguments, and passes first argument as
// `this` (i.e. first parameter) and rest arguments as second parameter
myFunc.call(newObject, 'foo', 'bar'); //outputs: newObject "foo" "bar"
// .apply works little differently: first argument is the value to be passed
// as `this` and second argument, which should be an array -- of which, each
// item is passed in as each parameter to the callee function
myFunc.apply(newObject, ['foo', 'bar']); //outputs: newObject "foo" "bar"
// REFERENCES:
// http://www.jblotus.com/2013/01/13/common-javascript-gotchas/#highlighter_282407
// http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment