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
檢查,它提供什麼功能。我在上面提出了我的短路假設,以及爲什麼這並不完全合理。
請介意添加MDN頁面的鏈接嗎? –
@mortezaT [MDN:Function.prototype.bind()填充工具(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill) –
大概的副本[ MDN Function.prototype.bind綁定函數稱爲構造](http://stackoverflow.com/questions/23693282) –