1

Why do we need apply method inside the constructor to invoke any method defined on the prototype object?

Code working:

    function Test(){
    this.x = [];
    this.add.apply(this,arguments);
    }

    Test.prototype.add = function(){
    for(var i=0; i < arguments.length; i++){
    this.x.push(arguments[i]);
    }
    }

    var t = new Test(11,12)

    t.x          //[11,12]  this is fine
    t.x.length   //2 this is also fine

But when i directly call add inside constructor

Code not working:

    function Test(){
    this.x = [];
    this.add(arguments);
    }

    Test.prototype.add = function(){
    for(var i=0; i < arguments.length; i++){
    this.x.push(arguments[i]);
    }
    }

    var t = new Test(11,12);
    t.x.length; //1 Not added all elements why?

enter image description here

4

1 回答 1

5

This hasn't got anything to do with prototypes, it's got to do with how apply takes an array and then uses the values as arguments to the function to call. In this case, if you do

this.add(arguments);

It's doing exactly that. Calling add with the first argument being an array-like object, and you end up with x being an array where the first element is an array. new Test(1, 2, 3) will result in x = [ [1, 2, 3] ] (the inner array is actually an Arguments object, but it resembles an array). However if you do

this.add.apply(this, arguments);

It's essentially doing

this.add(arguments[0], arguments[1], arguments[2], ...);

And this way x ends up being an array of those elements, instead of an array within an array. I.e., with new Test(1, 2, 3) you'll get x = [1, 2, 3], without the extra array inbetween.

于 2012-12-31T12:34:45.780 回答