如何在不使用eval的情况下检查变量是否是javascript类方法中的函数

如何在不使用eval的情况下检查变量是否是javascript类方法中的函数,javascript,Javascript,我创建这个类是为了检查函数是否已加载。它工作得很好,只是我想避免使用eval从变量计算函数名。我非常感谢你在这方面的帮助。谢谢 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.

我创建这个类是为了检查函数是否已加载。它工作得很好,只是我想避免使用eval从变量计算函数名。我非常感谢你在这方面的帮助。谢谢

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

假设您尝试检测的脚本将位于全局对象上,则按
s拆分字符串,并检查全局对象上是否存在嵌套属性:

类脚本加载器{
构造函数(propsStr,最大值){
this.propsStr=propsStr;//作为字符串传递的函数名
this.count=0;//初始计数开始值
this.max\u try=max\u try;//尝试的最大次数
}
waitForScriptToLoad(){
"严格使用",;
const possibleFn=this.propsStr.split('.').reduce((a,prop)=>(a?[prop]),globalThis);
if(可能的类型fn==“函数”){
可能fn();
}否则{
如果(this.count{
这个.count++;
this.waitForScriptToLoad();
},100);//等待100毫秒,然后重试
}
}
}
}
//动态加载脚本:
设置超时(()=>{
window.obj={};
}, 50);
设置超时(()=>{
window.obj.nested={
fn:()=>console.log('fn')
};
}, 150);
const loadData=newscriptloader('obj.nested.fn',3);

loadData.waitForScriptToLoad()有效,谢谢!但首先我要了解reduce是如何工作的。
loadData = new scriptLoader('Worker.fetch_form_data', 3);
loadData.waitForScriptToLoad();