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.");
}
}
retur开发者_运维问答n kdApi;
})();
new kdApi("w", "b");
When I run this, I want to get both class and function doesn't exist message but instead I get w is not defined error. What am I doing wrong? Also, can I do it without 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);
Live demo: http://jsbin.com/ufubi5/5
Tested under Chrome 10.0.642.2 dev
The standard way of seeing it a function exists in JavaScript is to test if it is in the current scope. Hence the idiom:
if (funcName) {
funcName();
}
I believe there is something similar to see if it is a constructor function, but I'm not sure.
精彩评论