如果由两个字符串组成,则存在Javascript检查功能

时间:2013-08-31 18:07:17

标签: javascript typescript

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

如果我取消注释,那么typeof(controller + "Controller")始终是一个字符串(预期)。

如果我对代码发表评论并运行此代码,那么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);
    }
};

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

2 个答案:

答案 0 :(得分:1)

怎么样

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

答案 1 :(得分:0)

使用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) 
  }
}