2013-03-15 91 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