[英]Is there any meaningful difference bind() vs arrow function + call()?
給定 ES6 代碼
let a = new SomeClass();
let b = new AnotherClass();
let x = a.someMethod.bind(b, 1, 2, 3);
let y = () => a.someMethod.call(b, 1, 2, 3);
x
和y
之間有什么有意義的區別嗎? 我知道bind()
是很多舊的 function 但是現在有沒有必要在箭頭函數上使用它?
至少對我來說,箭頭 function 語法比bind()
語法更容易閱讀,特別是因為你通常可以避免在實踐中使用call()
,而this
仍然具有詞匯上下文的正常含義。 例如, bind()
) 在實踐中會有更好的性能(CPU 還是 RAM)?
let a = function(){}; let b = function(){}; am = 1 bm = 2 a.someMethod = function(x, y, z){ return this.m + x + y + z } let x = a.someMethod.bind(b, 1, 2, 3); let y = () => a.someMethod.call(b, 1, 2, 3) console.log( x(1,2,3) ) console.log( y(1,2,3) ) function goBind() { for (var i = 0; i < 1000000; i++) { x(1,2,3) } } function goArrow() { for (var i = 0; i < 1000000; i++) { y(1,2,3) } } function race() { var start = performance.now(); goBind(); console.log('bind: ' + (performance.now() - start)); start = performance.now(); goArrow() console.log('arrow: ' + (performance.now() - start)); start = performance.now(); goBind(); console.log('bind: ' + (performance.now() - start)); start = performance.now(); goArrow() console.log('arrow: ' + (performance.now() - start)); console.log('------'); }
<button onclick="race()">RACE!</button>
不管性能如何,對於某些用例,箭頭 function 不能代表相同的邏輯。 例如,當你使用 Promises 時,你可以有這樣的東西(這個例子的源代碼):
function CommentController(articles) {
this.comments = [];
articles.getList()
.then(function (articles) {
return Promise.all(articles.map(function (article) {
return article.comments.getList();
}));
})
.then(function (commentLists) {
return commentLists.reduce(function (a, b) {
return a.concat(b);
});
})
.then(function (comments) {
this.comments = comments;
}.bind(this));
}
如果最后一個bind(this)
被刪除,請注意區別。 沒有簡單的方法可以使用箭頭 function 表示法來更改它而無需大量修改代碼。 不過,對於這樣的代碼,我個人更喜歡使用帶有變量名的閉包而不是this
。
此外, bind()
可以用於部分應用程序,對於具有函數式編程背景的人來說可能更容易閱讀。
另一方面,如果稍后修改a.someMethod
,使用bind()
的版本將不會看到更改,因為它在綁定期間引用了 function。 調用y()
時,帶有 lambda function 的變體將看到a.someMethod
的當前值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.