我经常在我的模块/插件/库中使用这种模式:
var borrow = function( obj, funcName, funcArg ){
return function(){
/// convert arguments to array
var args = Array.prototype.slice.call( arguments );
/// add in our fixed arg 'change'
args.unshift( funcArg );
/// execute the function
return obj[funcName].apply( obj, args );
}
}
self.change = borrow( cb, 'on', 'change' );
这应该意味着您可以在构造函数之外调用:
module.change( callbackFunction );
这基本上具有直接借用jQuery函数的效果,但是用您选择的特定元素包装它。以上将您的事件侦听器直接传递给复选框,就像您直接键入以下内容一样:
cb.on( 'change', callbackFunction );
您可以改进上述内容以接受多个固定参数,如下所示:
var borrow = function( obj, funcName ){
/// convert arguments to array
var args1 = Array.prototype.slice.call( arguments );
/// remove the first two args (obj & funcName)
/// which means we now have an array of left over arguments
/// we'll treat these as 'fixed' and always passed to the
/// 'borrowed' function.
args1.shift(); args1.shift();
/// return a closure containing our 'borrowed' function
return function(){
/// convert arguments to array
var args2 = Array.prototype.slice.call( arguments );
/// create a new array combined from the fixed args and the variable ones
var args = args1.concat( args2 );
/// execute the function
return obj[funcName].apply( obj, args );
}
}
进一步的改进(摆脱班次)将是这样的:
var borrow = function( obj, funcName ){
/// convert arguments to array and remove first two arguments
var args1 = Array.prototype.slice.call( arguments, 2 );
/// return a closure containing our 'borrowed' function
return function(){
/// convert arguments to array
var args2 = Array.prototype.slice.call( arguments );
/// create a new array combined from the fixed args and the variable ones
var args = args1.concat( args2 );
/// execute the function
return obj[funcName].apply( obj, args );
}
}