【问题标题】:Javascript constructor to access own private method?Javascript构造函数访问自己的私有方法?
【发布时间】:2016-08-01 00:36:33
【问题描述】:

我的班级中有一个我不想公开的方法。我想知道是否可以从构造函数中访问该方法?

例如:

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

})();

如果之前有人问过这个问题,我很抱歉,但这可能吗?

【问题讨论】:

  • 对不起,我的代码有错误,分配给原型的函数应该是自调用的。我正在尝试“Revealing Prototype Pattern”——它对我来说还是新的。
  • 我现在明白了。您可以在外部范围内声明toggleOption,在 IIFE 内,它仍然是“私有的”。但是这种“私有”和“公有”的概念并没有很好地转移到 JS 中,不是经典的 OOP 意义上的。
  • 看看this
  • 当整个类已经合二为一时,无需将原型对象的创建包装在 IIFE 中。

标签: javascript class oop methods scope


【解决方案1】:

是的,有可能 :D

演示: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)

})();   

【讨论】:

  • 注意:最重要的部分是.bind(this),它使toggleOption函数可以使用对象实例。
【解决方案2】:

这取决于你为什么要公开这个。

例如,如果您想公开该变量以进行单元测试,您可以执行以下操作:

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


return {
    getOptions: getOptions,
    gprivate: gprivate
};

【讨论】:

    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2011-02-05
    • 2018-12-12
    相关资源
    最近更新 更多