如何在Javascript中创建静态变量?


当前回答

你可以这样想。在<body></body>中放置标记<p id=“静态变量”></p>并设置其可见性:隐藏。

当然,您可以使用jquery来管理前一个标记中的文本。实际上,这个标签成为你的静态变量。

其他回答

我没有在任何答案中看到这个想法,所以只是将其添加到列表中。如果是重复的,请告诉我,我会删除它并对另一个进行投票。

我在我的网站上创建了一种超级全球化。由于每次页面加载时都会加载几个js文件,而其他几十个js文件只加载在一些页面上,所以我将所有“全局”函数都放在一个全局变量中。

在我第一个包含的“全局”文件的顶部是声明

var cgf = {}; // Custom global functions.

然后我删除了几个全局助手函数

cgf.formBehaviors = function()
{
    // My form behaviors that get attached in every page load.
}

然后,如果我需要一个静态变量,我只需将其存储在范围之外,例如文档就绪或行为附件之外。(我使用jquery,但它应该在javascript中工作)

cgf.first = true;
$.on('click', '.my-button', function()
{
    // Don't allow the user to press the submit twice.
    if (cgf.first)
    {
        // first time behavior. such as submit
    }
    cgf.first = false;
}

这当然是一个全局的,而不是静态的,但由于它在每次加载页面时都会重新初始化,所以它可以达到相同的目的。

试试这个:

如果我们定义一个属性并重写其getter和setter以使用Function Object属性,那么理论上可以在javascript中使用一个静态变量

例如:

函数Animal(){if(isNaN(this.totalAnimalCount)){this.totalAnimalCount=0;}this.totalAnimationCount++;};Object.defineProperty(动画原型,“totalAnimalCount”{获取:函数(){return Animal['totalAnimalCount'];},集合:函数(val){动物['totalAnimalCount']=val;}});var cat=新动画();console.log(cat.totalAnimationCount)//将产生1var dog=新动画();console.log(cat.totalAnimationCount)//将产生2等。

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.

这会得到相同的结果——只是这次返回的是递增的值,而不是显示。

您可以通过IIFE(立即调用的函数表达式)执行此操作:

var incr = (function () {
    var i = 1;

    return function () {
        return i++;
    }
})();

incr(); // returns 1
incr(); // returns 2