简体   繁体   中英

Javascript constructor to access own private method?

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?

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)

})();   

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

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