在函数的第一个实例上设置变量值 运行
Set Value of Variable on first instance of function running
例如,我有一个变量,每次函数为 运行 时它都应该递增。我希望变量最初被赋予 0 的值,但每次调用该函数时都会增加 1。我不想给变量全局范围,但是很明显,如果我在函数中声明它,每次调用时它都会重置为 0。
在 Javascript?
中有没有一种简单有效的方法来做到这一点?
我的Javascript:
function myFunction(){
var i=0;
//Body of function
i++;
}
您可以像这样在函数对象本身上设置值
function myFunction() {
myFunction.i = myFunction.i || 0;
myFunction.i++;
}
或者,您可以像这样使用闭包
var myFunction = (function () {
var i = 0;
return function () {
// `myFunction` will be this function only and it increments the
// `i` from the enclosed function.
i++;
}
})();
例如,我有一个变量,每次函数为 运行 时它都应该递增。我希望变量最初被赋予 0 的值,但每次调用该函数时都会增加 1。我不想给变量全局范围,但是很明显,如果我在函数中声明它,每次调用时它都会重置为 0。 在 Javascript?
中有没有一种简单有效的方法来做到这一点?我的Javascript:
function myFunction(){
var i=0;
//Body of function
i++;
}
您可以像这样在函数对象本身上设置值
function myFunction() {
myFunction.i = myFunction.i || 0;
myFunction.i++;
}
或者,您可以像这样使用闭包
var myFunction = (function () {
var i = 0;
return function () {
// `myFunction` will be this function only and it increments the
// `i` from the enclosed function.
i++;
}
})();