0

I have a method in my class that I do not want to be public. I'm wondering if it's possible to access the method from the constructor?

For example:

(function () {
    var Config = function() {
        this.data = this.getOptions();
        var options = document.querySelector('.options');
        options.addEventListener('click', this.toggleOption, false);
    };

    Config.prototype = function() {
        var getOptions = function() {
            // public method
        },

        toggleOption = function() {
            // private method
        };

        return {
            getOptions: getOptions
        };
    }();

    var config = new Config();

})();

My apologies if this has been asked before, but is this possible?

j_quelly
  • 1,399
  • 4
  • 16
  • 37
  • Sorry there was a mistake in my code, the function assigned to the prototype is supposed to be self-invoking. I'm trying out the "Revealing Prototype Pattern" --it's still new to me. – j_quelly Apr 11 '16 at 02:08
  • I see now. You can declare `toggleOption` in the outer scope, inside the IIFE, it will still be "private". But this "private" and "public" concept doesn't transfer to JS too well, not in the classical OOP sense. – elclanrs Apr 11 '16 at 02:10
  • Have a look at [this](http://stackoverflow.com/q/9248655/1048572). – Bergi Apr 11 '16 at 03:07
  • 1
    There's no need to wrap the prototype object creation in an IIFE when the whole class already is in one. – Bergi Apr 11 '16 at 03:08

2 Answers2

1

Yes, it is possible :D

Demo: https://jsbin.com/xehiyerasu/

(function () {
  var Config = (function () {
    function toggleOption () {
      console.log('works')
    }

    var Config = function() {
        this.data = this.getOptions();
        var options = document.querySelector('.options');
        options.addEventListener('click', toggleOption.bind(this), false);
    };

    Config.prototype = (function() {
        var getOptions = function() {
            // public method
        };
        return {
            getOptions: getOptions
        };
    })();

    return Config;
  })();

  var config = new Config();

  console.log('Is toggleOption private? ', !config.toggleOption)

})();   
  • Note: most important part is `.bind(this)` which makes the object instance available to the `toggleOption` function. –  Apr 11 '16 at 02:16
0

It depends on WHY you'd like to expose this.

If, for instance, you want to expose that variable for unit testing purposes, you could do something like:

if (window.someUnitTestingGlobal) {
  var gprivate = {
    toggleOption: toggleOption
  };
}


return {
    getOptions: getOptions,
    gprivate: gprivate
};
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74