在Javascript中的对象文字中按名称(作为字符串)调用函数

时间:2012-05-08 12:07:39

标签: javascript oop

我目前正在使用JS构建一些东西并遇到以下情况:

// these are set programmatically, not like this, just using as an example
var data = {'someData':'blah'};
var widget = 'NameOfWidget';
var command = 'someFunctionName';

// there is a base object that has all widgets and their commands as child objects
// format would be like: UBER.WidgetName.command(data);
// here is how I have tried to call it thus far
UBER[widget][command](data);
window['UBER'][widget][command](data);

我觉得我已经接近搞清楚了,只需要一些帮助来弄清楚确切的语法!谢谢!

2 个答案:

答案 0 :(得分:0)

你有没有理由不这样做?

window[UBER.widget.command](data);

编辑:我看到你正在尝试做什么,这个答案目前不正确应该有效,因为我理解你正在尝试做什么。

答案 1 :(得分:0)

尝试:

UBER['widget']['command'](data); 
window['UBER']['widget']['command'](data);

UBER.widget.command(data);
window.UBER.widget.command(data);

假设命令是一个函数,小部件和UBER是对象,窗口['UBER'] = UBER。

使用括号语法引用对象属性时,需要使用字符串。如果使用.语法,则必须使用非Javascript中的保留字的合法字符串文字。

例如:

var command = function(){return 5},
    widget = {},
    UBER = {};
UBER.widget = widget;
widget.command = command;
console.log(UBER['widget']['command']()); // prints 5 to Chrome's developer console or firebug