简体   繁体   中英

How to convert object value to function in javascript?

I want to used objects to store function name and another properties which i will used it to load jS script by Jquery getScript. I have used conditional by inAarray to check if an object is existing in this array I will call that scrip and execute that function (func) but I still have stack to convert that object value to a function for execution after JS scrip load within status success.

    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;
                    }
                });
            }
        });
    }

Since vals.function holds the name of the function, and the function should already be defined by the loaded script, do not use the following to get the function object:

var fun = new Function(vals.function);

Instead, use:

var fun = window[vals.function]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM