繁体   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