美文网首页
30-seconds-of-code学习笔记(1

30-seconds-of-code学习笔记(1

作者: 灰色的龙猫 | 来源:发表于2017-12-28 10:52 被阅读0次

最近在看30-seconds-of-code的代码,觉得好优雅,打算一个一个学习然后记下笔记

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 ]

这个很简单,其实就是运行 call(key, ...args)(context) 输出正确内容,即

console.log(call('map', x=>2 * x)([1,2,3]))

麻烦点的写法

var call = function(key) {
    var args = Array.prototype.slice.call(arguments, 1)
    return function(context) {
        return context[key].apply(context, args)
    }
}

再转成es6

const call = (key, ...args) => {
    return (context) => {
        return context[key](...args)
    }
}

然后我们再去掉可去掉的return和括号去掉就变成了最开始的样子

    const call = ( key, ...args ) => context => context[ key ]( ...args );

下面两个同理~ 今天结束~

相关文章

网友评论

      本文标题:30-seconds-of-code学习笔记(1

      本文链接:https://www.haomeiwen.com/subject/yypmgxtx.html