function Set() { // This is the constructor
this.values = {};
this.n = 0;
this.add.apply(this, arguments); // All arguments are values to add
}
// Add each of the arguments to the set.
Set.prototype.add = function() {
/* Code to add properties to the object's values property */
return this;
};
This is the beginning of the code used in "Javascript: The Definitive Guide" to create a 'Set' Class. I've tried to rationalize the necessity of the apply()
function in the constructor but can not figure it out for the life of me.
this.add.apply(this, arguments);
if the add()
function is already a method called by 'this
' then what purpose or use is the core apply()
function fulfilling. Thanks in advance to anyone who attempts to explain this to me
http://jsfiddle.net/Marlin/Ydwgv/ - Full Example from Javascript: The Definitive Guide
Summary. The apply() method invokes a function with a given this value and arguments provided as an array. The apply() method is similar to the call() method excepts that it accepts the arguments of the function as an array instead of individual arguments.
A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.
Call invokes the function and allows you to pass in arguments one by one. Apply invokes the function and allows you to pass in arguments as an array. Bind returns a new function, allowing you to pass in a this array and any number of arguments.
The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
"if the add() function is already a method called by 'this' then what purpose or use is the core apply() function fulfilling."
So that the arguments
can be passed on as an entire collection. Useful if Set
accepts an indefinite number of arguments.
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