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?

This hasn’t got anything to do with prototypes, it’s got to do with how
applytakes an array and then uses the values as arguments to the function to call. In this case, if you doIt’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 inx = [ [1, 2, 3] ](the inner array is actually an Arguments object, but it resembles an array). However if you doIt’s essentially doing
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 getx = [1, 2, 3], without the extra array inbetween.