参与者模式(participator):在特定的作用域中执行给定的函数,并将参数原封不动地传递。
js中的call和apply方法可以使在特定作用于中执行某个函数并传入参数,但添加的事件回调函数不能移除,需要借助参与者模式,其实就是bind方法,实现需要一个闭包
function bind(fn,context){
return function(){
return fn.apply(context,arguments);
}
}
var demoObj = { title: '例子' }
function demoFn(){
console.log(this.title);
}
var bindFn = bind(demoFn,demoObj);
demoFn(); //undefined
bindFn(); //例子
函数柯里化
对函数的参数分割,根据传递参数的不同,让一个函数存在多种状态。
重构bind
function bind(fn,context){
let firstArg = Array.prototype.slice.call(arguments,2);
return function(){
let addArgs = Array.prototype.slice,call(arguments);
let allArgs = firstArg.concat(addArgs);
return fn.apply(context,allArgs);
}
}
//浏览器兼容版本
if (!Function.prototype.bind) {
Function.prototype.bind = function (context) {
let self = this;
let firstArg = Array.prototype.slice.call(arguments,1);
return function () {
let secArg = Array.prototype.slice.call(arguments);
let finishArg = firstArg.concat(secArg);
return self.apply(context,finishArg);
}
}
}
通过运用参与者模式,使得事件绑定功能更加完善,参与者模式是两种技术的结晶:函数绑定和函数柯里化。早期浏览器并未提供bind方法,为了使添加的事件可以移除,事件回调函数中够访问到事件源,并且可以向事件回调函数中传入自定义数据,才发明了函数绑定和函数柯里化技术。