如何检查类和函数的存在?

时间:2011-01-26 05:41:33

标签: javascript

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的情况下执行此操作吗?

2 个答案:

答案 0 :(得分:2)

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 dev下测试

答案 1 :(得分:1)

在JavaScript中看到一个函数的标准方法是测试它是否在当前范围内。因此成语:

if (funcName) {
    funcName();
}

我相信有类似的东西,看它是否是一个构造函数,但我不确定。