简体   繁体   中英

Javascript: check if function exists, rename if so and create function from string

I am trying to get JS to check for a function if it exists, if it does then it renames the string then creates the function based on that string. I got the first part I just can figure out how to create the function name based on a string:

var myMicro = 'getMicro';

if (typeof window[myMicro] === "function") {
    myMicro = 'getMicro2';
} else {
    myMicro = 'getMicro';
}

function window[myMicro] (obj, place, func, params, finishFUNC) {

}

The first part works, but creating the function with this string doesn't seem to work afterwords.

You can probably do this:

window[myMicro] = function (obj, place, func, params, finishFUNC) {

}

It is good not to overwrite global variables as well:

var myMicro = "getMicro" in window ? "getMicro2" : "getMicro";
window[myMicro] = function(obj, place, func, params, finishFUNC) {
    // ...
};

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