Let's take a look at this code:
var mainFunction = function() { altFunction.apply(null, arguments); }
The arguments that are passed to mainFunction
are dynamic -- they can be 4 or 10, doesn't matter. However, I have to pass them through to altFunction
AND I have to add an EXTRA argument to the argument list.
I have tried this:
var mainFunction = function() { var mainArguments = arguments; mainArguments[mainArguments.length] = 'extra data'; // not +1 since length returns "human" count. altFunction.apply(null, mainArguments); }
But that does not seem to work. How can I do this?
Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help.
args is a rest parameter. It always has to be the last entry in the parameter list and it will be assigned an array that contains all arguments that haven't been assigned to previous parameters. It's basically the replacement for the arguments object. Instead of writing function max() { var values = Array. prototype.
Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With