![](/img/trans.png)
[英]What is the difference between `Function('return this')` and `function() {return this}`?
[英]What is the difference between the return from bind and the result of using function()
綁定的返回值和通過function()創建等效項的結果之間有什么區別? 有什么有效的區別嗎? (我不是在問bind
的上下文保留屬性)。 是否有任何技術/性能原因使您可能偏愛一種方法。
即
var myFunc = foo.bind(undefined, bar);
VS
var myFunc = function() { foo.call(undefined, bar) };
有什么有效的區別嗎?
是否有任何技術/性能原因使您可能偏愛一種方法。
第二個版本包括一個附加的函數調用。
沒有技術上的差異,但是在性能和無錯誤上有所不同。 一些最好的開發人員已經編寫了function.prototype中的所有函數,它們遵循了所有程序員期望的特定規范。 並且當然已經通過了很好的測試。
總是最好不要重新發明輪子,並且永遠正確的是,這個開發人員將比我們做得更好。
注意1: 現在I8的使用率低於0.3% ,因此請不要介意它是否不支持綁定。 您的網站很有可能不支持很多功能。
注意2:chrome中bind的實現是這樣的:
在chrome中用dev-console編寫: Function.prototype.bind
,結果是
function(e,t){var n=this;return null!=t&&(t=Array.from(t)),function(){return n.apply(e,t||arguments)}}
獎勵:這是一個非常相似的實現,用於更簡潔的代碼(從Prototype.js復制.bind方法):
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
#bind
在IE8中不起作用。 因此,在這種情況下,您可以使用第二個示例=),但最好在此處實現#bind
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.