I’m trying to learn Javascript by reading the source code of Fabric.js.
In file util/lang_array.js there is a method that looks like this:
var slice = Array.prototype.slice;
function invoke(array, method) {
var args = slice.call(arguments, 2), result = [ ];
for (var i = 0, len = array.length; i < len; i++) {
result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
}
return result;
}
I don’t understand the statement var args = slice.call(arguments, 2). The particular part that puzzles me is passing 2 as the second argument (considering arguments being [array, method] then arguments[2] should be null). I looked up the JS reference and came to the conclusion that it basically initializes args to an empty array.
Then why not simply var args = []?
Thanks.
This line is there to pick up any extra arguments supplied to the function.
Those extra arguments are then passed to the specified method in the
.applycall.NB: JS does not check the formal parameters of functions. Omitted parameters will be
undefined, and extra parameters will be (mostly) ignored, but available through theargumentspseudo-array.I’m unsure why the code bothers checking
args.lengthto see whether to call.applyor.call– it looks like premature optimisation.