Check if a private function exists inside an object in JavaScript

387 views Asked by At

How can I check if a private function exist inside an object?

var myObj = function(){
    var myFunc = function(){};

    var init = function(){
        //has myFunc been defined?
    }
}

I know that I can do this:

if (typeof myFunc == 'function') { 
    //myFunc exist
}

But this is checking the global scope.
How can I limit this to my objects scope?

Here is the most simplified case that i need:

var myComponent = function () {
    var exportExcel = function () {

    };
    this.export = function (type) {
        if('export'+type is a private function in this scope){
            window["export"+type]()//but in local scope;
        }
    }
};

And here is my work around for now :

var myComponent = function () {
    var Exports = {
        Excel: function () {

        }
    };

    this.export = function (type) {
        if (Exports.hasOwnProperty(type)) {
            Exports[type]();
        } else {
            alert('This Export type has not been implemented Yet ! or it never will ... how knows? well i don\'t ...');
        }
    }
};
2

There are 2 answers

4
AudioBubble On

As you probably noticed:

function myFunc () {};

function myObj () {
    function init () {
        if (myFunc) // passes
    };
}

You could cheat a bit :-|

function myObj () {
    var isdef = { myFunc: true };
    function myFunc () {};
    function init () {
        if (isdef.myFunc) // do something
    };
}

I wonder why one would do that though.

1
Ja͢ck On

Bases on the extra information given, the most practical pattern is what you're calling the "temporary workaround": keeping your functions in a private object, keyed by type.

var myComponent = function () {
    var exporters = Object.create(null, {
        "Excel": function () {
            // do magic export here
        }
    });

    this.export = function (type) {
        if (type in exporters) {
            // defined locally
            return exporters[type].call(this); // binding is optional
        } else {
            // no export for you!
        }
    }
};

This prevents two things:

  1. Referencing the function via string composition,
  2. Querying the global scope (or, actually, any scope in between your component and the global scope).

This may not be your design principle, you could further extend this code to allow for adding / removing exporters.