Javascript反射,调用带有字符串的方法

Javascript reflection, call a method with a string

本文关键字:字符串 方法 反射 调用 Javascript      更新时间:2023-09-26
    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()视为此问题的潜在解决方案,但似乎无法让它们中的任何一个工作。有人对我的特定对象场景的语法有任何指导吗?

使用括号表示法而不是点表示法:

orderdet[strMethod]();

这应该有效。 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.
    }