Created
April 21, 2012 17:21
-
-
Save RedWolves/2438558 to your computer and use it in GitHub Desktop.
Converting function arguments that weren't formally declared to accept into an Array.
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
// Create a reference to the Array.slice "static" method. | |
var slice = [].slice; | |
// call some function with one required argument. | |
var somefunction = function (requiredArgument) { | |
// arguments is an Array-like local variable available within all functions. | |
// arguments refers to the function's arguments within the function, you can use the | |
// arguments object if you call a function with more arguments than it is formally declared to accept. | |
// https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments | |
// slice method can also be called to convert Array-like objects / collections to a new Array. | |
// You just bind the method to the object. The arguments inside a function is an example of | |
// 'array-like object'. Binding can be done with the .call function of Function.prototype | |
// and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. | |
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice#Array-like_objects | |
var args = slice.call(arguments, 1); | |
console.log (args); // ["1", "2", "3"] | |
} | |
somefunction("i am required", "1", "2", "3"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment