-
Notifications
You must be signed in to change notification settings - Fork 0
Home
This repository is part of a larger project!
📕 The Javascript apply method is similar to the method call. The big difference is the ability of apply to take an array of different numbers of arguments:
function manyArguments(a,b,c,d)
{
return a + b + c + d;
}
//Outputs 10
manyArguments.apply(this,[1,2,3,4]);
This could be important for the use of variadic functions or also known as variable-arity functions. An example for a variadic function could be one which calculates the sum of a series of numbers:
//Variadic Function
function calculateSum(listOfNumbers)
{
var sum = 0;
for(var i = 0; i < listOfNumbers.length; i++)
{
sum += listOfNumbers[i];
}
return sum;
}
//Outputs 6
calculateSum([1,2,3]);
With the use of arguments and apply, the function calculateSum could be written and called like follows:
//Variadic Function - no parameter(s)
function calculateSum()
{
var sum = 0;
//"arguments" is an implicit local variable
//which handles the arguments of its function
for(var i = 0; i < arguments.length; i++)
{
sum += arguments[i];
}
return sum;
}
//Outputs 6
calculateSum.apply(null, [1,2,3]);
📕 The null receiver in calculateSum.apply could also be replaced by an object, keyword this(see first code listing) or by primitive values.
The user interaction part should look like the content as seen below by starting "index.html" in a web browser.
The colored areas are just for a better readability in the wiki and are not part of the content. To use the project just download the files and execute "index.html". Note that all files(folders "wiki_images" and "PaintNET" excluded) should be placed in the same folder so that the functionality of the code is guaranteed.
The "PaintNet" folder contains a .pdn file which can be opened and altered with PaintNET for simple picture editing.
This knowledge was gained:
-
Effective JavaScript "68 Specific Ways to Harness the Power of JavaScript" by David Herman
-
Why would you pass 'null' to 'apply' or 'call'? asked by Antonio Pavicevac-Ortiz and answered by Christos