2013-03-15 88 views
0
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使用和Array.prototype.slice.call

回答

2

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

MDN

arguments对象不是数组。它与阵列类似,但 没有任何阵列属性,除了length

+0

Array.prototype.slice.call如何将其克隆到数组对象中....参数如何作为数组链接对象。 – theJava 2013-03-15 12:21:02

+1

@theJava其工作的最佳描述在这里:http://stackoverflow.com/a/7057090/1249581。 – VisioN 2013-03-15 12:24:50

+0

MDN包含一些关于slice doc中的类似数组的行为,FWIW:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice#Array-like – 2013-08-29 03:06:13