1
我想检查一下我是否可以使用以下对象中的函数。如何找出对象中是否存在声明的函数?
我的目标代码:
var joe = joe || {};
(function(window, document, undefined) {
'use strict';
joe.test = (function()
{
// --------------------------
var testing = function() {
console.log("testing is here");
};
// --------------------------
return {
testMe:testing
}
})();
}(window, document));
我的跳棋:没有人工作。
if ((window.joe == 'undefined') && (window.joe.test == 'undefined')) {
console.log("1:not here ");
} else {
console.log("1:there ");
}
if ((typeof joe == "object") && (joe.test.testMe in window)) {
console.log("2:there");
} else{
console.log("2:not there");
}
if ((typeof joe == "object") && (joe.test.testMe == "function")) {
console.log("3:there");
} else {
console.log("3:not there");
}
如何才能知道函数joe.test.testMe存在,但未声明时未发生错误?
THX的回答:如果我删除了乔对象,我会收到以下错误:的ReferenceError:乔没有定义。那就是我想避免的。 – hamburger
我不认为我完全理解这一说法。但是你确实需要在每个语句之前使用'typeof'。我会把它放在我的答案中来展示它应该如何看待。 –