简体   繁体   English

如何在不使用 eval 的 javascript class 方法中检查变量是否为 function

[英]How to check if variable is function in a javascript class method without using eval

i have created this class to check if the function has been loaded.我创建了这个 class 来检查 function 是否已加载。 It works fine, except that I want to avoid using eval to evaluate the function name from a variable.它工作正常,除了我想避免使用 eval 从变量中评估 function 名称。 I appreciate any help with this.我很感激这方面的任何帮助。 Thanks.谢谢。

class scriptLoader {

constructor(fn, max_try) {        
    this.fn = fn; //the func name being passed as a string
    this.count = 0; //init count start value                
    this.max_try = max_try; //the max times to try
}



waitForScriptToLoad() {           
      'use strict';        
        let my_function = eval(this.fn); //this evaluate the string, i.e 'myfunc' to myfunc()                       
      if(typeof my_function === "function") {                        
        my_function();
    } else {                                    
        if(this.count<this.max_try) {
            var that = this;
            setTimeout(function() {that.count++; that.waitForScriptToLoad();},100); //wait 100ms and try again            
        } else {                
            return false;                
        }            
    }
}

} }

I instantiate the class like so:我像这样实例化 class :

loadData = new scriptLoader('Worker.fetch_form_data', 3);
loadData.waitForScriptToLoad();

Assuming that the script you're trying to detect will be located on the global object, split the string by .假设您尝试检测的脚本将位于全局 object 上,将字符串拆分为. s and check to see if the nested property exists on the global object: s 并检查嵌套属性是否存在于全局 object 上:

 class scriptLoader { constructor(propsStr, max_try) { this.propsStr = propsStr; //the func name being passed as a string this.count = 0; //init count start value this.max_try = max_try; //the max times to try } waitForScriptToLoad() { 'use strict'; const possibleFn = this.propsStr.split('.').reduce((a, prop) => (a?.[prop]), globalThis); if (typeof possibleFn === "function") { possibleFn(); } else { if (this.count < this.max_try) { console.log('retrying'); setTimeout(() => { this.count++; this.waitForScriptToLoad(); }, 100); //wait 100ms and try again } } } } // Dynamic loading of script: setTimeout(() => { window.obj = {}; }, 50); setTimeout(() => { window.obj.nested = { fn: () => console.log('fn') }; }, 150); const loadData = new scriptLoader('obj.nested.fn', 3); loadData.waitForScriptToLoad();

Also note:另请注意:

  • If using ES2015+ syntax (which you are, and you should be,), best to use const rather than let if you don't require reassignment - avoid var如果使用 ES2015+ 语法(你是,你应该是),最好使用const而不是let如果你不需要重新分配 - 避免var
  • In ES2015+, better to use an arrow function than the that = this antipattern在 ES2015+ 中,最好使用箭头 function 而不是that = this反模式
  • Remember to declare your variables when using them - your loadData is implicitly global since you didn't declare it (consider enabling strict mode at the top level)记住在使用它们时声明你的变量 - 你的loadData是隐式全局的,因为你没有声明它(考虑在顶层启用严格模式)

暂无
暂无

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

相关问题 Javascript:在没有eval的情况下调用变量中定义的函数 - Javascript: call a function defined in a variable without eval 如何在不使用eval()的情况下将完整功能字符串转换为javascript函数 - how to convert a full function string to a javascript function without using eval() 使用toString和eval()运行Javascript类函数 - Run Javascript Class function using toString and eval() 使用javascript而不使用eval()检查文本有效的javascript - Check is text valid javascript using javascript without using eval() JavaScript,在不使用eval的情况下将私有函数作为公共方法内的字符串调用(Revealing pattern) - JavaScript, call private function as a string inside public method without using eval (Revealing pattern) Kinetic.js / Javascript:在不使用eval()的情况下将变量作为属性调用? - Kinetic.js / Javascript: calling a variable as a property without using eval()? 在不使用eval的情况下在方法函数中传递固定参数 - Passing fixed arguments in method function without using eval 如何在没有eval的情况下在coffeescript中调用新变量类名 - How to call New variable Class Name in coffeescript without eval 如何在 JavaScript 中不写“eval”的情况下执行“eval” - How to execute “eval” without writing “eval” in JavaScript 如何将两个变量作为单个字符串传递给Repeater中的javascript函数:使用DataBinder.Eval - how to pass two variable as single string to javascript function in Repeater : using DataBinder.Eval
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM