【问题标题】:Javascript check function exists if made up of two strings如果由两个字符串组成,则存在 Javascript 检查功能
【发布时间】:2021-06-15 15:14:59
【问题描述】:

我正在使用 Garber-Irish 实现(使用 typescript),并且我有以下 Typescript 代码,我想在其中检查 controller + "Controller" 的类型是否是有效函数。

如果我取消注释该评论,那么 typeof(controller + "Controller") 始终是一个字符串(意料之中)。

如果我注释代码并运行此 if 则 new window[controller + "Controller"] 在窗口没有有效功能时返回错误,例如 fooController

var util = {
    exec: function (controller: string, action: string) {
        //if (typeof(controller + "Controller") !== 'function') return;

        var ctrlClass = new window[controller + "Controller"];
        if (ctrlClass === undefined) return; //this is most likely redundant

        if (action === undefined)
            ctrlClass.init();
        else {
            if (ctrlClass[action] && typeof ctrlClass[action] == "function") {
                ctrlClass[action]();
            }
        }
    },

    init: function () {
        var body = document.body,
            controller = $("body").data("controller").toLowerCase(),
            action = $("body").data("action").toLowerCase();

        GlobalApp.common.init();
        util.exec(controller);
        util.exec(controller, action);
    }
};

所以我的问题是如何检查一个函数是否存在,如果它由两个字符串组成,例如“家”+“控制器”。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    怎么样

    typeof window[controller+"Controller"] === "function"
    

    【讨论】:

    • 我以为我试过了,但注意到我试过typeof(new( window[controller+"Controller"])我忘了删除新的!您的版本似乎工作正常。谢谢
    • 没问题。当您尝试一堆不同的组合时,很容易错过一些东西。
    • 是的,函数式语言:)
    【解决方案2】:

    使用 typeof,显示我的代码:

    class Manage{
      public test(data: any){
        console.log(data)
      }
    }
    
    let manage = new Manage();
    
    for(let i in manage){
      if(typeof (manage as any)[i] === 'function'){
        console.log('function')
      }
      else{
        console.log(typeof i) 
      }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      相关资源
      最近更新 更多