我尝试构建一个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
}
}