[英]How would you implement a javascript function so that it has a notion of how many times it has been called?
console.log(foo()()); //it has to print '2'
console.log(foo()()()); //it has to print '3'
console.log(foo()()()()); //it has to print '4'
您将如何实现function foo(){}
来实现后一种行为?
这是我为解决这个问题所做的尝试:
foo.i = 0;
function foo(){
foo.i++;
return foo;
}
var f = foo()()()();
console.log(f.i); //prints 4
但是当然
var f = foo()()()();
console.log(f.i); //prints 4
不等于
console.log(foo()()()());
您可以使用内部函数来递增计数器并实现toString
方法以获取计数。
如果期望值是原始类型,则调用toString
。
function foo() { function x() { count++; return x; } var count = 1; x.toString = function () { return count; } return x; } console.log(foo()); // 1 console.log(foo()()); // 2 console.log(foo()()()); // 3 console.log(foo()()()()); // 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.