我得到了一个字符串:
settings.functionName + '(' + t.parentNode.id + ')';
我想翻译成一个函数调用,像这样:
clickedOnItem(IdofParent);
当然,这必须用JavaScript来完成。当我在设置上做警报时。functionName + '(' + t.parentNode.id + ')';似乎每件事都是正确的。我只需要调用它转换成的函数。
传说:
settings.functionName = clickedOnItem
t.parentNode.id = IdofParent
因为我讨厌eval,而且我不是一个人:
var fn = window[settings.functionName];
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
Edit: In reply to @Mahan's comment:
In this particular case, settings.functionName would be "clickedOnItem". This would, at runtime translate var fn = window[settings.functionName]; into var fn = window["clickedOnItem"], which would obtain a reference to function clickedOnItem (nodeId) {}. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(t.parentNode.id), which equals clickedOnItem(t.parentNode.id), which was what the OP wanted.
更完整的例子:
/* Somewhere: */
window.settings = {
/* [..] Other settings */
functionName: 'clickedOnItem'
/* , [..] More settings */
};
/* Later */
function clickedOnItem (nodeId) {
/* Some cool event handling code here */
}
/* Even later */
var fn = window[settings.functionName];
/* note that settings.functionName could also be written
as window.settings.functionName. In this case, we use the fact that window
is the implied scope of global variables. */
if(typeof fn === 'function') {
fn(t.parentNode.id);
}
在使用CommonJS规范的javascript中,比如node.js,你可以做我下面展示的事情。这对于通过字符串访问变量非常方便,即使它没有在窗口对象上定义。如果有一个名为MyClass的类,定义在一个名为MyClass.js的CommonJS模块中
// MyClass.js
var MyClass = function() {
// I do stuff in here. Probably return an object
return {
foo: "bar"
}
}
module.exports = MyClass;
然后你可以在另一个名为MyOtherFile.js的文件中做这个漂亮的巫术
// MyOtherFile.js
var myString = "MyClass";
var MyClass = require('./' + myString);
var obj = new MyClass();
console.log(obj.foo); // returns "bar"
CommonJS如此令人愉快的另一个原因。