hamburger
hamburger

Reputation: 1435

How to find out if there is a function declared in an object?

I would like to check if I can use an function from the following object.

My Object-Code:

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));

My checkers: No one is working.

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

How can I find out that the function joe.test.testMe is there, without getting an error when it is not declared?

Upvotes: 1

Views: 34

Answers (1)

Cayce K
Cayce K

Reputation: 2338

CSS Tricks did a tiny article on this here

They use::

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

If it exists as a function then it will run. If it doesn't exist typeof var returns 'undefined'

if(typeof joe.test.testMe == 'function') {
    joe.test.testMe();
}

Your checks should be::

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

Upvotes: 1

Related Questions