使用模块模式在私有方法中更改公共变量

时间:2013-10-13 16:07:10

标签: javascript module-pattern

我有下一个代码:

var Test = (function() {
    var counter = 0;
    var increaseCounter = function() {
        this.counter += 1;
    }
    increaseCounterPrivate = function() {
        // does not affect this.counter! //
        increaseCounter();
    }
    var counterLogic = function() {
        // ... do something here ... //
        increaseCounterPrivate();
    }
    return {
        counter: counter,
        increaseCounter: increaseCounter,
        counterLogic: counterLogic
    };
});

var test = new Test();
test.increaseCounter();
console.log(this.counter); //1
test.counterLogic();
console.log(this.counter); //1 again, should be 2

上面的代码没有意义(它仅用于测试),但我想知道一般情况下我是否可以调用public方法,它将调用私有方法,最终将更改公共变量。 如何重写以显示正确的值?

0 个答案:

没有答案