Last active
August 29, 2015 14:06
-
-
Save troyscott/47c6f8816c08edd9fecd to your computer and use it in GitHub Desktop.
JavaScript: apply versus call // source http://jsbin.com/nejufu/4
This file contains hidden or 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
// 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