我經常用這個模式我的模塊/插件/庫中:
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);
}
}
感謝。這裏是一個小演示http://jsbin.com/eqovak/4/edit – Daniel
@Daniel酷:)沒問題......它是相當煩人的'參數'對象不支持正常的數組方法,直到你已經轉換它 - 否則代碼將相當整齊。哦,順便說一句,我已經添加了一個更好的版本,擺脫了數組shift()的需要。 – Pebbl
再次感謝,這是一個非常優雅的解決方案。 http://jsbin.com/eqovak/5/edit – Daniel