Why the apply () function is required in the constructor

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 values property */
    return this;
};

This is the beginning of the code used in the Javascript: The Definitive Guide to create the Set class. I tried to rationalize the need for a function apply()in the constructor, but I can't figure it out for me.

this.add.apply(this, arguments);

if the function is add()already a method called ` this`, then what purpose or use is the core of the apply()execution of the function. Thanks in advance to everyone who is trying to explain this to me.

http://jsfiddle.net/Marlin/Ydwgv/ - Full Javascript Example: Complete Guide

+5
source share
5 answers

", add() , 'this', core().

arguments . , Set .

+7

- , (, , ;-). apply, , "".

, apply, - * (arguments counts), [n1, n2, ... n3] f, f(n1, n2, ... n3). apply " ", ( , add ). . /.

,

var s = new Set(1, 2, 3)

var s = new Set()
s.add(1, 2, 3)

.

.


* FireFox 4 . :

f.apply(context, Array.prototype.slice.call(arguments, 0))
+2

, , , , :

this.add.apply(this, [1,2,3,4]);
....
function add(one, two, three, four)

,

+1

apply , .

:

function add(a, b) {
    return a+b;
}

var values = [1,2];

alert(add.apply(this, values));

3.


, , , , , add .

, :

var stack = new Set(1,2,3,4,5,6,7,8,9);

add, :

this.add(1,2,3,4,5,6,7,8,9);
+1

Using syntax .apply()allows you to pass an array of arguments to the called function. In this case, it passes the object arguments, which means that it calls add()with any and all parameters that were passed to the Set constructor function. Thus, you can create new Set objects with an arbitrary number of values, specifying, for example,

var mySet = new Set(13,42,18,19,44,11,5);

And all of these values ​​will be passed to add().

+1
source

All Articles