简体   繁体   中英

jQuery - Checking if function is defined

I can't for the life of me figure out how to do this. I have my jquery name spaced a certain way in that it is prefixed with NWO.{function-name} to make it a little more organized. So it looks something like this:

var NWO = NWO || {}

NWO.Chat = (function() {
   return{
   init : function($objects) {
   console.log('do something');         
   } }
}
}());

jQuery(document).ready(function(){
  NWO.Chat.init($('div').find('a.chat'));
});

Now the chat element isn't on every page so on certain pages where the chat link doesn't exist I get a NWO.Chat is undefined. I thought for the pages that don't have the chat link I could do something like this to avoid the error.

if(jQuery().NWO.Chat){ NWO.Chat.init($('div').find('a.chat')); }

or

if($.fn.NWO.Chat){ NWO.Chat.init($('div').find('a.chat')); }

But neither seems to be working I still get the error. How do I avoid the js error when the chat link isn't on the page. I've been banging my head for hours. Thanks in advance.

NWO is not a jQuery plugin so have nothing to do with jQuery, it is a object(looks like a global scope), so you could just do

if (NWO && NWO.Chat && typeof NWO.Chat.init == 'function') {
    NWO.Chat.init($('div').find('a.chat'));
}

您可以使用typeof通过将其与“ undefined”进行比较来检查对象是否已定义

if(typeof NWO.Chat != 'undefined')

You can also just fix the root of your problem:

NWO.Chat = (function() {
   return{
   init : function($objects) {
   console.log('do something');         
   } }
}      //  <<-----------REMOVE THIS CURLY BRACE
}());

That extra curly at the end ( } ) is the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM