简体   繁体   English

Javascript:检查函数是否存在,如果是则重命名并从字符串创建函数

[英]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. 我试图让JS检查函数是否存在,如果它存在,那么它重命名字符串然后根据该字符串创建函数。 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) {
    // ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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