2012-12-14 26 views
4

我想委託幾個方法從一個JavaScript對象到另一個。所以我想過使用元編程並沒有像代表那樣定義幾種方法。到目前爲止,我結束了這種方法:JavaScript中元編程的動態參數?

function delegate_to(_method, _obj) { 
    return function(_args) { // One parameter, what's about multiple parameters? 
    return _obj[_method](_args) 
    } 
} 

因此,作爲一個例子,代碼應該如何工作的:

var that = {} 
var delegate = {} 
that.foo = function(_message) { console.log("foo: " + _message) } 
that.bar = function(_message) { console.log("bar: " + _message) } 
that.baz = function(_message) { console.log("baz: " + _message) } 

function delegate_to(_method, _obj) { 
    return function(_args) { // One parameter, what's about multiple parameters? 
    return _obj[_method](_args) 
    } 
} 

['foo', 'bar', 'baz'].forEach(function(method) { 
    delegate[method] = delegate_to(method, that) 
}) 

delegate.foo('Hello JS') // foo: Hello JS 
delegate.bar('Hello JS') // bar: Hello JS 
delegate.baz('Hello JS') // baz: Hello JS 

代碼的工作,但什麼,如果我想委託,做的方法有多個參數? n參數如何?是否有可能將代碼更改爲具有任意數量的參數?這是否在任何瀏覽器中運行?

問候,賴

+0

我不會把這個元編程。這是簡單的函數式編程。 – JohnB

回答

1

函數方法稱爲「應用」通過可變數量的參數爲一個數組。請參閱MDC:Function.apply

您可以將傳遞給函數到一個數組的所有參數由
Array.prototype.slice.call(arguments, 0)

使用這兩個校長,我已經修改你的代碼的參數拍攝的多個號碼。見JSBin http://jsbin.com/iwiwix/3/watch

相關代碼片段:

delegate.foo('Hello JS', "from foo"); // foo: Hello JS 



function delegate_to(_method, _obj) { 
    return function() { 
    var argArray = Array.prototype.slice.call(arguments, 0); 
    return _obj[_method].apply(_obj, argArray); 
    }; 
} 



that.foo = function() { console.log("foo: " + arguments[0] + ' ' + arguments[1]); }; 
2

嘗試這種情況:

function delegate_to(_method, _obj) { 
    return function() { 
    return _obj[_method].apply(_obj, [].slice.call(arguments)) 
    } 
} 
+0

參數不是數組,您無法合法調用切片。 – closure

+0

@raghavv是的,你是對的,我忘記了,編輯已經完成。 – dencey

+0

更好的方法是Array.prototype.slice.call(參數,0),因爲您不必要地構造空數組。 – closure