您可以将函数视为对象并赋予它们“成员变量”。这里我们在fact 中使用了一个内部函数,但不是仅仅将其声明为局部变量(var loop = ...),而是使用对象语法(fact.loop = ...)将其定义放在函数之外。这让我们实质上“导出”了fact 的内部loop 函数,以便它可以被函数doubleFact 重用。
var fact = function(n) {
return fact.loop(n, 1);
};
fact.loop = function(n, acc) {
if (n < 1) {
return acc;
} else {
return fact.loop(n-1, acc * n);
}
};
var doubleFact = function(x) {
return fact.loop(x * 2, 1);
};
console.log(fact(5)); // 120
console.log(doubleFact(5)); // 3628800
同样的想法也可以用来维护状态。
var countCalled = function() {
console.log("I've been called " + (++countCalled.callCount) + " times.");
};
countCalled.callCount = 0;
countCalled(); // I've been called 1 times.
countCalled(); // I've been called 2 times.
countCalled(); // I've been called 3 times.
如果您希望能够实例化多个,每个都有自己的状态,试试这个:
var CallCounter = function(name) {
var f = function() {
console.log(name + " has been called " + (++f.callCount) + " times.");
};
f.callCount = 0;
return f;
};
var foo = CallCounter("foo");
var bar = CallCounter("bar");
foo();
foo();
bar();
foo();
bar();
bar();
bar();
console.log(foo.callCount);
console.log(bar.callCount);
输出:
foo has been called 1 times.
foo has been called 2 times.
bar has been called 1 times.
foo has been called 3 times.
bar has been called 2 times.
bar has been called 3 times.
bar has been called 4 times.
3
4