所以似乎Javascript中没有函数静态变量.我试图在函数内增加一个变量,但我不想这样做:
function countMyself() {
if ( typeof countMyself.counter == 'undefined' ) {
// It has not... perform the initilization
countMyself.counter = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我想用闭包来做,但我很难理解这些.
有人在另一个问题中提出这个建议:
var uniqueID = (function() {
var id = 0;
return function() { return id++; };
})();
Run Code Online (Sandbox Code Playgroud)
但是当我提醒uniqueID时它所做的就是打印这一行:return function(){return id ++; };
所以我想知道如何在不污染全局范围的情况下增加函数中的变量.
你必须实际调用 uniqueID - 你不能只是引用就好像它是一个变量:
> uniqueID
function () { return id++; }
> uniqueID()
0
> uniqueID()
1
Run Code Online (Sandbox Code Playgroud)