【发布时间】:2012-12-02 05:20:18
【问题描述】:
我想将几个方法从一个 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 参数呢?是否可以将代码更改为具有任意数量的参数?这是在任何浏览器中运行的吗?
问候,雷纳
【问题讨论】:
-
我不会称之为元编程。这是简单的函数式编程。
标签: javascript dynamic parameters delegates metaprogramming