我必须构建一个执行某些任务的函数。
任务将是函数的参数,很可能是字符串数组。 它可能看起来像这样:
['refresh', 'close', 'show']
字符串对应于实际方法。
是否可以通过使用数组的字符串以某种方式执行方法?
答案 0 :(得分:2)
简答:
烨:
var method = "refresh";
yourObject[method]();
答案很长:
这是可能的,但您的方法必须被命名空间。
如果您在浏览器上下文中,则以下示例将起作用,因为每个全局函数都是window
的属性:
function refresh() {
// do it
}
var method = "refresh";
window[method]();
// or maybe
var yourObject = { refresh: function() { ... } };
yourObject[method]();
但是,以下内容不起作用(我正在显示它,因为闭包是javascript中的常见模式):
(function() {
function refresh() {
// do it
}
var method = "refresh";
// which object contains refresh...? None!
// yourObject[method]();
})();
答案 1 :(得分:1)
如果您的方法附加到窗口对象,那么您可以执行以下操作:
var methods = [ 'refresh', 'close', 'show' ];
for( var i in methods ) {
funk = window[ methods[ i ] ];
if( typeof funk === 'function') {
window.funk();
}
}
否则,如果您的方法是另一个对象的方法,您可以轻松地用您的对象替换窗口。