Lets take a look at this code:
var mainFunction = function() {
altFunction.apply(null, arguments);
}
The arguments that are passed to \"mainF
The arguments
object isn't an array; it's like an array, but it's different. You can turn it into an array however:
var mainArguments = [].slice.call(arguments, 0);
Then you can push another value onto the end:
mainArguments.push("whatever");
var myABC = '12321';
someFunction(result, error, myCallback.bind(this, myABC));
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Use Array.prototype.push
[].push.call(arguments, "new value");
There's no need to shallow clone the arguments
object because it and its .length
are mutable.
(function() {
console.log(arguments[arguments.length - 1]); // foo
[].push.call(arguments, "bar");
console.log(arguments[arguments.length - 1]); // bar
})("foo");
From ECMAScript 5, 10.6 Arguments Object
- Call the
[[DefineOwnProperty]]
internal method on obj passing"length"
, the Property Descriptor{[[Value]]: len, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}
, and false as arguments.
So you can see that .length
is writeable, so it will update with Array methods.
//
// var
// altFn = function () {},
// mainFn = prefilled( altFn /* ...params */ );
//
// mainFn( /* ...params */ );
//
//
function prefilled ( fn /* ...params */ ) {
return ( function ( args1 ) {
var orfn = this;
return function () {
return orfn.apply( this, args1.concat( cslc( arguments ) ) );
};
} ).call( fn, cslc( arguments, 1 ) );
}
// helper fn
function cslc( args, i, j ) {
return Array.prototype.slice.call( args, i, j );
}
// example
var
f1 = function () { console.log( cslc( arguments ) ); },
F1 = prefilled( f1, 98, 99, 100 );
F1( 'a', 'b', 'c' );
//
// logs: [98, 99, 100, "a", "b", "c"]
//
//
In this case it could be more comfortable to use call()
instead of apply()
:
function first(parameter1, parameter2) {
var parameter3 = "123";
secondFunction.call(
this,
parameter1,
parameter2,
parameter3);
},
arguments
is not a pure array. You need to make a normal array out of it:
var mainArguments = Array.prototype.slice.call(arguments);
mainArguments.push("extra data");