为什么我们需要在构造函数中使用 apply 方法来调用原型对象上定义的任何方法?

P K*_*P K 1 javascript

为什么我们需要在构造函数中使用 apply 方法来调用原型对象上定义的任何方法?

代码工作:

    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
Run Code Online (Sandbox Code Playgroud)

但是当我直接在构造函数中调用 add 时

代码不起作用:

    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?
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Mat*_*nen 5

这与原型没有任何关系,它与如何apply获取数组然后将值用作要调用的函数的参数有关。在这种情况下,如果你这样做

this.add(arguments);
Run Code Online (Sandbox Code Playgroud)

正是这样做的。调用 add 时第一个参数是一个类似数组的对象,最终 x 是一个数组,其中第一个元素是一个数组。new Test(1, 2, 3)将导致x = [ [1, 2, 3] ](内部数组实际上是一个 Arguments 对象,但它类似于一个数组)。但是,如果你这样做

this.add.apply(this, arguments);
Run Code Online (Sandbox Code Playgroud)

它本质上是在做

this.add(arguments[0], arguments[1], arguments[2], ...);
Run Code Online (Sandbox Code Playgroud)

这样 x 最终成为这些元素的数组,而不是数组中的数组。即,new Test(1, 2, 3)你会得到x = [1, 2, 3],中间没有额外的数组。