最近在看30-seconds-of-code的代碼飞涂,覺得好優(yōu)雅旦部,打算一個一個學(xué)習(xí)然后記下筆記
call
const call = ( key, ...args ) => context => context[ key ]( ...args );
Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
這個很簡單,其實就是運(yùn)行 call(key, ...args)(context) 輸出正確內(nèi)容,即
console.log(call('map', x=>2 * x)([1,2,3]))
麻煩點(diǎn)的寫法
var call = function(key) {
var args = Array.prototype.slice.call(arguments, 1)
return function(context) {
return context[key].apply(context, args)
}
}
再轉(zhuǎn)成es6
const call = (key, ...args) => {
return (context) => {
return context[key](...args)
}
}
然后我們再去掉可去掉的return和括號去掉就變成了最開始的樣子
const call = ( key, ...args ) => context => context[ key ]( ...args );
下面兩個同理~ 今天結(jié)束~