我是JavaScript的初学者,请耐心等待=)
我正在尝试编写一个计算它被调用次数的函数。到目前为止我所拥有的是一个具有明确增加的计数器的函数:
var increment = function () {
var i = 0;
this.inc = function () {i += 1;};
this.get = function () {return i;};
};
var ob = new increment();
ob.inc();
ob.inc();
alert(ob.get());
但我想知道如何只调用ob();
,因此该函数可以自动增加对自身的调用。这是可能的,如果是的话,怎么样?
答案 0 :(得分:8)
var increment = function() {
var i = 0;
return function() { return i += 1; };
};
var ob = increment();
答案 1 :(得分:1)
ob = function f(){
++f.i || (f.i=1); // initialize or increment a counter in the function object
return f.i;
}
答案 2 :(得分:1)
还有新的 Generator functions ,它提供了一种简单的方式来编写计数器:
function* makeRangeIterator(start = 0, end = 100, step = 1) {
let iterationCount = 0;
for (let i = start; i < end; i += step) {
iterationCount++;
yield i;
}
return iterationCount;
}
const counter = makeRangeIterator();
const nextVal = () => counter.next().value;
console.log("nextVal: ", nextVal()); // 0
console.log("nextVal: ", nextVal()); // 1
console.log("nextVal: ", nextVal()); // 2
console.log("nextVal: ", nextVal()); // 3
答案 3 :(得分:0)
为任何功能包装一个计数器:
/**
* Wrap a counter to a function
* Count how many times a function is called
* @param {Function} fn Function to count
* @param {Number} count Counter, default to 1
*/
function addCounterToFn(fn, count = 1) {
return function () {
fn.apply(null, arguments);
return count++;
}
}
答案 4 :(得分:0)
一个班轮选项:
const counter = ((count = 0) => () => count++)()
用法示例:
> counter()
0
> counter()
1
> counter()
2
> counter()
3
> counter()
4
> counter()
5
> counter()
6