在我們實際使用中,經常用ES6的箭頭函式來代替Function.prototype.bind()
.
1.提取物件的方法
如果將一個物件的方法作為回撥函式傳入,你需要定義一個確定的this
,否則它將作為一個函式來執行(this值可能是undefined, 也可能是全域性物件).例如:
obj.on('anEvent', console.log.bind(console))
另一種解決方案就是使用箭頭函式:
obj.on('anEvent', x => console.log(x))
譯者注: 原文評論中也提到了ES7的繫結運算子, 如下:
obj.on('anEvent', ::console.log)
2.this作為引數
下面的程式碼展示了一個小技巧:對於一些方法,你可能不需要用bind()
來為回撥函式繫結this
,這類方法允許你在額外的引數中定義this
的值..filter()
就是這樣一類方法:
const as = new Set([1, 2, 3]);
const bs = new Set([3, 2, 4]);
const intersection = [...as].filter(bs.has, bs);
// [2, 3]
如果說你使用了箭頭函式,程式碼會更加清晰易讀:
const as = new Set([1, 2, 3]);
const bs = new Set([3, 2, 4]);
const intersection = [...as].filter(a => bs.has(a));
// [2, 3]
3.部分賦值
bind()
允許你設定一個函式部分引數的值,你可以藉由一個已有的函式,為它設定部分引數的值,然後建立一個新的函式:
function add(x, y) {
return x + y;
}
const plus1 = add.bind(undefined, 1);
再一次,我找到了使用箭頭函式簡化它的方法:
const plus1 = y => add(1, y);