如何在javascript中将对象值转换为函数?

时间:2016-06-28 03:09:10

标签: javascript jquery

我想使用对象存储函数名称和另外一个属性,我将用它来加载Jquery getScript的jS脚本。 我使用了inAarray中的条件来检查这个数组中是否存在一个对象我将调用该脚本并执行该函数(func)但我仍然有堆栈将该对象值转换为一个执行的函数在JS脚本加载状态成功后。

    function fetchingData(n_source_id, types, not_id) {

   var data = {
        'Loan Repayment':{
            url:'/js/load/loan/loan_repayment.js',
            func:'repayment'// name of function which I will call after JS file successfully loaded
        },
        'Reject Repayment':{
            url:'/js/load/loan/repay_change_till_acc.js',
            func:'changeTill'// name of function which I will call after JS file successfully loaded
        },
        'Issue Till': {
            url: '/js/load/issueTill.js',
            func: 'issueTill'// name of function which I will call after JS file successfully loaded
        }
    };
        $.each(data, function(inx, vals) {

            var _type = inx;
            var url = vals;

            if ($.inArray(types, [_type]) >= 0) {

                ScriptRequire([vals.url], function(status) {

                    if (status === 'success') {

                        var fun = new Function(vals.function);

                        console.log(fun(n_source_id, types));
                        return fun;
                    }
                });
            }
        });
    }

1 个答案:

答案 0 :(得分:1)

由于vals.function包含函数的名称,并且该函数应该已经由加载的脚本定义,因此不要使用以下函数来获取函数对象:

var fun = new Function(vals.function);

相反,请使用:

var fun = window[vals.function];