I want to delegate several methods from one JavaScript-Object to another. So i thought about using metaprogramming to not have several methods be defined just as delegates. So far i ended up with this method:
function delegate_to(_method, _obj) {
return function(_args) { // One parameter, what's about multiple parameters?
return _obj[_method](_args)
}
}
So as an example-code how it should work:
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
The code does work, but what’s if i want to delegate a method that does have more than one parameter? How about n parameters? Is it possible to change the code to have any number of parameters? Is this running in any browser?
Regards, Rainer
Function has methods called ‘apply’ to pass variable number of parameters as an array. Refer MDC:Function.apply
You can convert all the parameters passed to a function into an array by
Array.prototype.slice.call(arguments, 0)Using these two principals, I have modified you code to taken multiple number of parameters. See the JSBin http://jsbin.com/iwiwix/3/watch
Relevant code extract: