简体   繁体   中英

Cleaner way to see if function is defined

Is there an easier way to check if a javascript function has already been called and is active besides what I have below, or is what I have below already optimized...

    var isDefined = function(func) {
       if(func !== undefined)
       {
          return true;
       }
       else
       {
          return false;
       }
     }

JavaScript does nothing to retain memory of a function having already been called. You can put a Boolean var flag outside of it, set it to true inside, and ensure its scope doesn't leak by putting it inside an IIFE, which may give you what you want.

If what you're doing is related to click/event listening, you may want to use something like JQuery's $.once() , which adds an event listener that removes itself after occurring once.

var isDefined = function(func) {
     return (func !== undefined);
}

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