如何在Javascript中创建静态变量?
当前回答
还有另一种方法,它解决了我浏览这个线程后的需求。这完全取决于您想要使用“静态变量”实现什么。
全局属性sessionStorage或localStorage允许在会话的生命周期内存储数据,或在明确清除之前存储不确定的更长时间。这允许在页面/应用程序的所有窗口、框架、选项卡面板、弹出窗口等之间共享数据,并且比一个代码段中的简单“静态/全局变量”功能强大得多。
它避免了顶级全局变量(如Window.myglobal)的范围、生存期、语义、动态等方面的所有麻烦。不知道它有多高效,但这对于以适度速度访问的少量数据来说并不重要。
轻松访问为“sessionStorage.mydata=anything”,并以类似方式检索。看见“JavaScript:最终指南,第六版”,David Flanagan,ISBN:978-0-596-80552-4,第20章,第20.1节。通过简单的搜索,或在O’Reilly Safaribooks订阅(价值黄金)中,可以轻松下载为PDF格式。
其他回答
Javascript中没有静态变量。这种语言是基于原型的面向对象的,因此没有类,而是对象“复制”自己的原型。
您可以使用全局变量或原型(向原型添加属性)来模拟它们:
function circle(){
}
circle.prototype.pi=3.14159
您可以利用JS函数也是对象这一事实,这意味着它们可以具有财产。
例如,引用Javascript中静态变量一文(现已消失)中给出的示例:
function countMyself() {
// Check to see if the counter has been initialized
if ( typeof countMyself.counter == 'undefined' ) {
// It has not... perform the initialization
countMyself.counter = 0;
}
// Do something stupid to indicate the value
alert(++countMyself.counter);
}
如果多次调用该函数,您将看到计数器正在递增。
这可能是一个比用全局变量替换全局命名空间更好的解决方案。
下面是基于闭包的另一种可能的解决方案:在javascript中使用静态变量的技巧:
var uniqueID = (function() {
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it.
这会得到相同的结果——只是这次返回的是递增的值,而不是显示。
{
var statvar = 0;
function f_counter()
{
var nonstatvar = 0;
nonstatvar ++;
statvar ++;
return statvar + " , " + nonstatvar;
}
}
alert(f_counter());
alert(f_counter());
alert(f_counter());
alert(f_counter());
这只是我在某处学到的另一种静态变量的方法。
可以在声明静态变量后重新分配函数
function IHaveBeenCalled() {
console.log("YOU SHOULD ONLY SEE THIS ONCE");
return "Hello World: "
}
function testableFunction(...args) {
testableFunction=inner //reassign the function
const prepend=IHaveBeenCalled()
return inner(...args) //pass all arguments the 1st time
function inner(num) {
console.log(prepend + num);
}
}
testableFunction(2) // Hello World: 2
testableFunction(5) // Hello World: 5
这使用。。。args比较慢,有没有办法第一次使用父函数的作用域而不是传递所有参数?
我的用例:
function copyToClipboard(...args) {
copyToClipboard = inner //reassign the function
const child_process = require('child_process')
return inner(...args) //pass all arguments the 1st time
function inner(content_for_the_clipboard) {
child_process.spawn('clip').stdin.end(content_for_the_clipboard)
}
}
如果要在作用域之外使用child_process,可以将其分配给copyToCclipboard的属性
function copyToClipboard(...args) {
copyToClipboard = inner //reassign the function
copyToClipboard.child_process = require('child_process')
return inner(...args) //pass all arguments the 1st time
function inner(content_for_the_clipboard) {
copyToClipboard.child_process.spawn('clip').stdin.end(content_for_the_clipboard)
}
}
当我看到这个时,我记得JavaScript闭包。。我是这样做的。。
function Increment() {
var num = 0; // Here num is a private static variable
return function () {
return ++num;
}
}
var inc = new Increment();
console.log(inc());//Prints 1
console.log(inc());//Prints 2
console.log(inc());//Prints 3