Javascript 如何确定对象中是否声明了函数?
我想检查是否可以使用以下对象中的函数 我的目标代码:Javascript 如何确定对象中是否声明了函数?,javascript,jquery,Javascript,Jquery,我想检查是否可以使用以下对象中的函数 我的目标代码: var joe = joe || {}; (function(window, document, undefined) { 'use strict'; joe.test = (function() { // -------------------------- var testing = function () { conso
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在那里,而不在未声明时出错?CSS Tricks就此发表了一篇小文章 他们使用:
if (typeof yourFunctionName == 'function') {
yourFunctionName();
}
如果它作为函数存在,那么它将运行。如果不存在typeof var
返回“未定义”
if(typeof joe.test.testMe == 'function') {
joe.test.testMe();
}
您的支票应该是:
if ((typeof window.joe == 'undefined') && (typeof window.joe.test == 'undefined')) {
console.log("1:not here ");
} else {
console.log("1:there ");
if ((typeof joe == "object")) {
console.log("2:there");
if ((joe.test.testMe == "function")) {
console.log("3:there");
} else {
console.log("3:not there");
}
} else{
console.log("2:not there");
}
}
谢谢你的回答:如果我删除joe对象,我将得到以下错误:ReferenceError:joe未定义。这就是我想要避免的。我不认为我完全理解这种说法。但您确实需要在每条语句之前使用
typeof
。我将把它放在我的答案中,以显示它应该是什么样子。