gpt4 book ai didi

Javascript反射,用字符串调用方法

转载 作者:行者123 更新时间:2023-11-30 07:40:20 25 4
gpt4 key购买 nike

    var OrderDetails = function () {
var orderdetails = {};
orderdetails.doSomething = function(){
alert('do something');
};
return orderdetails;
}

在代码的其他地方...

    processMethod('doSomething')

function processMethod(strMethod)
{
// strMethod = 'doSomething';
var orderdet = OrderDetails(); //not the exact instantiation, just illustrating it is instantiated
orderdet.strMethod(); //this is the line I'm stuck with.
}

我目前正在尝试通过它在 Javascript 中的字符串名称来调用方法。我已经将 apply、call 和 eval() 视为解决此问题的潜在解决方案,但似乎无法使它们中的任何一个起作用。对于我的特定对象场景,有人对语法有任何指导吗?

最佳答案

使用bracket notation而不是 dot notation :

orderdet[strMethod]();

关于Javascript反射,用字符串调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18781934/

25 4 0
文章推荐: java - java.sql.date 的 getter 和 setter
文章推荐: java - 如果 Gradle 中的字母全部大写,无法创建工作 jar 文件?
文章推荐: java - 分页点击页面索引始终仅加载第一页
文章推荐: javascript - 将具有特定类的文本添加到下拉列表