我有一个用 JavaScript 创建的模块。
var test = function () {
var validate = function () {
alert("fg");
};
return {
validate: validate
};
}();
现在,我可以使用字符串访问上述模块吗?例如:
$(function () {
var s = "test";
s.validate(); // error
});
嗯,我尝试过,但到目前为止还没有运气,因为“s”是字符串。有什么方法可以将此字符串转换为上述模块对象并访问 validate
方法吗?
最佳答案
您可以使用eval()
。
var test = function () {
var validate = function () {
alert("fg");
};
return {
validate: validate
};
}();
$(function () {
var s = eval("test"); //Here
s.validate();
});
旁注:
小心使用eval()
。来自 docs :
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.
关于javascript - 使用字符串变量访问 JavaScript 模块方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30662927/