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 - 如何检查类和函数是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4801696/