javascript - 使用闭包模拟私有(private)方法与对象中的公共(public)方法

标签 javascript oop closures private

MDN states闭包用于模拟模块模式的私有(private)方法:

var counter = (function () {
    var privateCounter = 0;

    function changeBy(val) {
        privateCounter += val;
    }

    return {
        increment: function () {
            changeBy(1);
        },
        decrement: function() {
            changeBy(-1);
        }
    };
}());

但是,除了使用模块模式,我们还可以创建一个类。与使用模块模式相比,创建类有什么优点?

function Counter() {
    var privateCounter = 0;

    function changeBy(val) {
        privateCounter += val;
    }

    this.increment = function() {
        changeBy(1);
    };

    this.decrement = function() {
        changeBy(-1);
    };
}

var counter = new Counter();

最佳答案

What is the advantage of creating a class over using the module pattern?

与使用模块模式相比,创建类的优点是您可以创建一个类的多个实例:

var counter1 = new Counter;
var counter2 = new Counter;

每个实例都有自己的一组私有(private)变量。

另一方面,当您使用模块模式时,您仅创建单个对象(通常称为单例、命名空间或模块)。同样,它有自己的一组私有(private)变量。

模块模式和类都有自己的用途。模块模式对于创建模块、管理器对象(其中必须仅存在一个实例)等很有用。

类模式对于创建相同类型的新数据结构非常有用。例如,链表数据结构将被建模为类,而不是单例或模块。

关于javascript - 使用闭包模拟私有(private)方法与对象中的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23064241/

相关文章:

c# - 如何扩展继承的方法而不是覆盖它?

java - 动态添加对象到数组

swift - 在方法参数中隐式解包可选闭包

php - 为什么我不能在非匿名函数中使用 'use'?

javascript - 将 Twitter 分享按钮(带有 JS 和所有内容)嵌入到 Mustache 模板中

javascript - 如何修复 "Npm ERR! JSON.parse Unexpected string in JSON at position 228.."

anti-patterns - 拥有无处不在的基础对象是一种反模式吗?

r - 为什么重复调用 lapply 后闭包中的变量值会丢失?

javascript - AngularJS 路由提供者 - 发布请求

JavaScript 或 jQuery 动态显示表单输入