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?

4
  • 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. Commented Apr 11, 2016 at 2: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. Commented Apr 11, 2016 at 2:10
  • Have a look at this. Commented Apr 11, 2016 at 3:07
  • 1
    There's no need to wrap the prototype object creation in an IIFE when the whole class already is in one. Commented Apr 11, 2016 at 3:08

2 Answers 2

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)

})();   
Sign up to request clarification or add additional context in comments.

1 Comment

Note: most important part is .bind(this) which makes the object instance available to the toggleOption function.
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
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.