Skip to content

Instantly share code, notes, and snippets.

@troyscott
Last active August 29, 2015 14:06
Show Gist options
  • Save troyscott/47c6f8816c08edd9fecd to your computer and use it in GitHub Desktop.
Save troyscott/47c6f8816c08edd9fecd to your computer and use it in GitHub Desktop.
JavaScript: apply versus call // source http://jsbin.com/nejufu/4
// apply versus call
// apply passes the array as a set of arguments to the function
function splat(fun) {
console.log('splat');
return function(array) {
console.log("fun.apply");
return fun.apply(null, array);
};
}
var numbers = [3,4];
var addIt = splat(function(x,y) {
console.log('addIt');
return x + y;
});
console.log(addIt(numbers));
// call passes the array as 1 argument
function printAll(fun) {
console.log('printAll');
return function() {
console.log("fun.call ...");
return fun.call(null, Array.prototype.slice.call(arguments));
};
}
var joinIt = printAll(function(array){
console.log('joinIt');
return array.join(' ');
});
var stuff = ['apple','orange','pear'];
console.log(joinIt(stuff));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment