bind绑定参数

const curry = (fn) => (...args)=>fn.bind(null,...args);

const  split = curry((splitOn, str) =>str.split(splitOn));

console.log(split(" ")("Hello JS")); // ["Hello","JS"]

这个函数初看一头雾水,split()()被连续调用,但是两个参数是怎么传递的,fn.bind(null,...args)不仅绑定了this,还能传递参数?,查了一下MDN

bind()方法会创建一个新函数。当这个新函数被调用时,bind()的第一个参数将作为它运行时的 this, 之后的一序列参数将会在传递的实参前传入作为它的参数。

前半句好理解,相信大家也也用到过,为函数绑定运行时的this

var name = "out value"
const obj = {
    name:"test bind",
    fn:function(){
        console.log(this.name);
    }
};

let f1 = obj.fn.bind(obj);
let f2 = obj.fn

f1()  // test bind
f2()  // out value

后半句,多余的参数将会当成新函数被调用时的参数,看例子

function test(one,two){
    console.log(one);
    console.log(two);

    console.log(arguments);
}

var tmp = test.bind(null,111);

tmp(2222);  // 111 222 {0:111,2:222}

111被当成了函数的第一个参数

回头看,这个函数写的很简洁 ,平时实现相同的方法,大概会这么写

function curry(fn){
	return function(splitOn){
		return function(str){
			return fn(splitOn,str);
		}
	}
}

ES6 写法

const curry = (fn) => (...agrs) => (str) => fn(...agrs,str)
const  split = curry((splitOn, str) =>str.split(splitOn));
console.log(split(" ")("Hello JS"))

总的来看区别不大,只是代码看起来更干净一点

posted @ 2016-12-30 09:24  一川碎石  阅读(416)  评论(0编辑  收藏  举报