【问题标题】:Using fn in Array.prototype.apply without thisargument?在没有这个参数的情况下在 Array.prototype.apply 中使用 fn?
【发布时间】:2014-01-13 21:47:25
【问题描述】:

我在看一个教程,为什么你可以调用 Array.prototype.pop.apply 或在没有指定 thisArg 的情况下调用?注意计算表达式中第 1 行和第 3 行的差异。

例如:

    var calculate = function () {
        var fn = Array.prototype.pop.apply(arguments);
        console.log(fn);
        return fn.apply(null, arguments);

    };

    var sum = function (x, y) {
        return x + y;
    };

    var diff = function (x, y) {
        return x - y;
    }


    var x = calculate(5, 3, sum);

如果我这样做,我会收到一个错误:Uncaught TypeError: Array.prototype.pop called on null or undefined Default.aspx:54 (anonymous function)

  var fn = Array.prototype.pop.apply(null, arguments);

【问题讨论】:

  • 你想在 arguments.pop 这样的参数上调用 pop ,这意味着 this 是参数。所以应该是Array.prototype.pop.apply(arguments);

标签: javascript


【解决方案1】:

Array.prototype.pop 在数组上被调用,通常不接受参数:

[1, 2, 3, 4].pop() //=> 4

Pop 是 Array 实例上的方法,因此它显式使用“this”。它可能有一些内部定义,比如这个可怕的近似值:

Array.prototype.pop = function() {
   var value = this[this.length - 1];
   delete this[this.length - 1];
   return value;
}

因此,当您使用为空的this 调用pop 时,它没有任何信息可访问,从不使用参数。在这种情况下,was said arguments 列表 this。您实际上是在调用arguments.pop(),但参数实际上没有 pop 方法,因此您在其上应用Array.prototype.pop 方法。

【讨论】:

  • 谢谢,你的解释很好,数组是一个特殊情况,它的参数是 this 参数。我必须让我的大脑围绕它
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2012-05-03
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多