我想委託幾個方法從一個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
參數如何?是否有可能將代碼更改爲具有任意數量的參數?這是否在任何瀏覽器中運行?
問候,賴
我不會把這個元編程。這是簡單的函數式編程。 – JohnB