Created
March 26, 2013 14:07
-
-
Save vishaltelangre/5245619 to your computer and use it in GitHub Desktop.
Difference between `call` and `apply` in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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