JS闭包:在对象中返回私有范围增量计数器值

时间:2015-02-09 15:25:21

标签: javascript

我尝试构建一个counterIncrement方法,可以被其他方法重用,并在每次调用方法时返回counter变量。

var myClass = {

    //counter method
    "counter": (function(text){
        var counter = 0;
        return function(text) {
            counter++
            console.log(text+counter);
        }
    })(), //how do you return this function without resetting the counter every time it is called?

    //every time this method is called the counter increases
    "myMethod": function(text) {
        myClass.counter(text);
    }
}

myClass.myMethod('the counter is at '); //the counter is at 1, 2, 3, etc.

基本上我尝试构建的是一个可重用的counter方法,它将实例化新的计数器值并相互增加。

var myClass = {

    "counter": (function(text){
        var counter = 0;
        var this.text = text;
        return function(this.text) {
            counter++
            console.log(this.text+counter);
        }
    })(),

    "firstMethod": function(text) {
        myClass.counter(text);
        //do something that uses the counter
    },

    "secondMethod": function(text) {
        myClass.counter(text);
        //do something completely different that instantiates new private counter
    }
}

0 个答案:

没有答案