Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the apply() function needed in the constructor

Tags:

javascript

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

like image 800
Marlin Avatar asked Sep 13 '11 03:09

Marlin


People also ask

What does apply () do in JavaScript?

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.

What is the purpose of constructor () function?

A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.

What is use of call () apply () bind () methods?

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.

What is the difference between call () and apply ()?

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.


1 Answers

"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.

like image 118
user113716 Avatar answered Sep 23 '22 19:09

user113716