Created
May 11, 2016 22:14
-
-
Save Klortho/67a2a774fd75ff1fb0bd8ab8041e24f0 to your computer and use it in GitHub Desktop.
Variable number of args in js, passing from function to function, manipulating, etc.
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
#!/usr/bin/env node | |
// Shows how to manipulate variable number of arguments, passing them | |
// around, etc. | |
// To just pass a variable number of arguments along, do this. This can be | |
// useful in a constructor, to pass the args to an init function, for example. | |
function passArgs() { | |
done.apply(this, arguments); | |
} | |
// To manipulate the list before passing it along, first turn it into an | |
// array. | |
function prependArg() { | |
var args = Array.prototype.slice.call(arguments); | |
args.unshift('(he said)'); | |
done.apply(this, args); | |
} | |
// Same, but a slightly different manipulation | |
function pushArg() { | |
var args = Array.prototype.slice.call(arguments); | |
args.push("again!"); | |
done.apply(this, args); | |
} | |
// This is just a wrapper for console.log. Again, passing args along ... | |
function done() { | |
console.log.apply(console, arguments); | |
} | |
// Try them out: | |
passArgs('and', 'now'); | |
prependArg('for', 'something'); | |
pushArg('completely', 'different'); | |
// Output: | |
// > and now | |
// > (he said) for something | |
// > completely different again! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍