簡體   English   中英

如何檢查類和函數的存在?

[英]How to check class and function existence?

var a, kdApi;
a = (function() {
  function a() {}
  a.prototype.b = function() {
    return "foo";
  };
  return a;
})();
kdApi = (function() {
  function kdApi(className, funcName) {
    if (typeof [className] !== "undefined" && ([className] != null)) {
      eval("cu= new " + className + "()");
      if (cu[funcName]) {
        console.log("class and function exists");
      } else {
        console.log("class does, function doesn't");
      }
    } else {
      console.log("both class and function doesn't.");
    }
  }
  return kdApi;
})();
new kdApi("w", "b");

當我運行此命令時,我想同時獲得類和函數不存在的消息,但我卻得到w未定義錯誤。 我究竟做錯了什么? 另外,我可以不用eval來做嗎?

var a, kdApi;
a = (function() {
    function a() {}
      a.prototype.c = 1;
      a.prototype.b = function() {
        return "foo";
      };
    return a;
})();

kdApi = (function() {
  function kdApi(className, funcName) {
    if (className != null && className in window) {
      if (funcName != null && funcName in window[className].prototype &&
          typeof window[className].prototype[funcName] == "function") {
        document.write("class and function exists");
      } else {
        document.write("class does, function doesn't");
      }
    } else {
      document.write("both class and function doesn't.");
    }
  }
  return kdApi;
})();

function testCF(clazz, func) {
  document.write("test for " + clazz + "." + func + "(): ");
  new kdApi(clazz, func);
  document.write("<br/>");
}

testCF("a", "b");
testCF("a", "c");
testCF("k", "b");
testCF("k", "c");
testCF(null, "c");
testCF("a", null);

現場演示: http//jsbin.com/ufubi5/5

經過Chrome 10.0.642.2開發人員測試

看到一個函數存在於JavaScript中的標准方法是測試它是否在當前范圍內。 因此,這個成語是:

if (funcName) {
    funcName();
}

我相信有類似的東西可以查看它是否是構造函數,但我不確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM