我想将几个方法从一个 JavaScript-Object 委托给另一个。所以我考虑使用元编程来不将几种方法定义为委托。到目前为止,我最终使用了这种方法:
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
参数呢?是否可以将代码更改为具有任意数量的参数?这是否在任何浏览器中运行?
问候,雷纳