调用方法和Array.prototype.slice.call的用法

usage of call method and Array.prototype.slice.call

本文关键字:call 用法 slice prototype 方法 Array 调用      更新时间:2023-09-26
if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
  };
}

我在看绑定函数的来源,我只是在想为什么他们在做一个Array.prototype.slice.call时,我可以直接做一个切片到我的arguments

因为arguments不是纯JavaScript数组,而是类数组对象。因此,为了对其进行更改,您必须使用Array.prototype.slice.call将其转换为实际数组。

从<<p> strong> MDN :

arguments对象不是Array。它类似于数组,但是除了length,没有其他Array属性。