2016-02-19 80 views
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存在,但未声明时未发生错误?

回答

1

CSS技巧做了这个here

他们使用::

if (typeof yourFunctionName == 'function') { 
    yourFunctionName(); 
} 

如果它存在的函数,那么它会运行一个小文章。如果它不存在typeof var回报'undefined'

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"); 
    } 
} 
+0

THX的回答:如果我删除了乔对象,我会收到以下错误:的ReferenceError:乔没有定义。那就是我想避免的。 – hamburger

+0

我不认为我完全理解这一说法。但是你确实需要在每个语句之前使用'typeof'。我会把它放在我的答案中来展示它应该如何看待。 –

相关问题