2016-07-16 28 views
6

MDN綁定polyfill如下所示。MDN綁定polyfill行的說明

我試圖找出的

this instanceof fNOP ? this : oThis 

目的在fToBind.apply調用。

我無法理解它。有人可以幫助解決一些問題嗎?

Function.prototype.bindMdn = 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 ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); 
    } 
    ; 
    if (this.prototype) { 
     // Function.prototype doesn't have a prototype property 
     fNOP.prototype = this.prototype; 
    } 
    fBound.prototype = new fNOP(); 
    return fBound; 
}; 

看來,如果綁定功能的實例作爲目標調用綁定功能時提供的是一個短路,但將typeof檢查應該抓住這一點,所以我不明白它的存在。

鏈接到MDN頁:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

編輯:這是建議的副本不同的問題。建議的副本會詢問爲什麼需要fNOP。我非常喜歡這一點。

這個問題是爲什麼需要instanceof檢查,它提供什麼功能。我在上面提出了我的短路假設,以及爲什麼這並不完全合理。

+1

請介意添加MDN頁面的鏈接嗎? –

+0

@mortezaT [MDN:Function.prototype.bind()填充工具(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill) –

+0

大概的副本[ MDN Function.prototype.bind綁定函數稱爲構造](http://stackoverflow.com/questions/23693282) –

回答

4

如果使用.bind的結果來創建新實例new

function TestClass(a,b,c,d) { 
} 

var TestClassBound = TestClass.bindMdn(null, 1, 2, 3); 

new TestClassBound(); 

然後this instanceof fNOPtrue

typeof this !== 'function'只是爲了測試它是否被稱爲函數的常規方式,而不是callapply或確保它不被複制到另一個對象原型。因此,它只能防止類似

Function.prototype.bind.call("Not a function", 1, 2, 3); 

或者

var testObj = {}; 
testObj.bind = Function.prototype.bind; 

testObj.bind(1,2,3); 

對於bind上的功能每一個正調用typeof this永遠是function

所以typeof this !== 'function'是檢查是否被調用的對象bind真的是一個功能。

fBindthis instanceof fNOP確保當使用結合的結果的行爲是正確的。

+0

_「fBind中的fNOP實例確保在使用綁定結果時行爲正確。」_哪種行爲?我的理解是,當你用'new'預先調用函數時,硬綁定函數將被一個綁定到硬綁定函數'this'的普通新對象調用,所以這個fNOP的實例與'[由於新的] instanceof fNOP'創建的普通對象,這意味着該條件將返回false(因爲'fNOP'的原型不存在於新創建的對象的原型鏈中),這意味着將設置this不正確 – Taurus

+0

所以'this'將被綁定到'oThis',如果使用'new'運算符,則不應該是這種情況,如果使用'new'運算符,'this'應該綁定到創建的新對象由新操作員在幕後操作。 – Taurus

+0

此外,'fNOP'代表什麼?我假設「f」是「功能」,那麼其他三個字母呢? – Taurus