Javascript 如何在Javascript中声明静态变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7307243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:42:50  来源:igfitidea点击:

How to declare a static variable in Javascript

javascriptprototype-oriented

提问by indianwebdevil

In the following code, I would like to have a counter to keep track of the number of Person objects created. This code is not doing so, how would I accomplish that?

在下面的代码中,我想要一个计数器来跟踪创建的 Person 对象的数量。这段代码没有这样做,我将如何做到这一点?

function Person(){
    this.name = "Peter";
    this.counter = this.counter + 1;
    alert(this.counter);
}

Person.prototype.counter = 0;

var p1 = new Person;
var p2 = new Person;

回答by James Allardice

function Person(){
    this.name = "Peter";
    Person.counter++;
    alert(Person.counter);
}

Person.counter = 0;

var p1 = new Person();
var p2 = new Person();

Make the "static" variable a property of the Personfunction, rather than the prototype, and use Personinstead of thisinside the constructor.

使“静态”变量成为Person函数的属性,而不是prototype, 并在构造函数内部使用Person而不是this

This is possible because JavaScript functions are first-class (i.e. they are objects), so can have properties of their own.

这是可能的,因为 JavaScript 函数是一流的(即它们是对象),因此可以拥有自己的属性。

Here's a working exampleof the above code.

这是上述代码的一个工作示例

回答by Pato

You can also make your counter variable "private", declaring it as local to a closure. It's the best way to have something similar to private - static variables:

您还可以将计数器变量设为“私有”,将其声明为闭包的本地变量。这是拥有类似于私有 - 静态变量的最佳方式:

var Person = (function() {

    var counter = 0;

    return function() {
        counter++;
        this.name = "Peter";
        alert(counter);
    };
})();


var p1 = new Person();
var p2 = new Person();

Example: https://jsfiddle.net/patodiblasi/67wucsqx/

示例:https: //jsfiddle.net/patodiblasi/67wucsqx/

回答by Raynos

There are no static properties. If you want you can store data on the Personfunction.

没有静态属性。如果需要,您可以在Person函数上存储数据。

function Person(){
    this.name = "Peter";
    Person.counter++;
    alert(Person.counter);
}

回答by Alex K.

For a static you can assign a property to the function object itself;

对于静态,您可以为函数对象本身分配一个属性;

Person.counter = 0;

And within the constructor increment with;

并在构造函数中递增;

Person.counter += 1;

You can also check-if-undefined and create Person.counterwithin the constructor

您还可以检查是否未定义并Person.counter在构造函数中创建

function Person(){
   if (typeof Person.counter === 'undefined')
      Person.counter = 0;
   else
      Person.counter += 1;
   ...

回答by shabunc

There is no such thing like static class variables/properties in js. The simplest approach is just use the "class" function as a namespace for static variables.

js 中没有像静态类变量/属性这样的东西。最简单的方法是使用“类”函数作为静态变量的命名空间。

It means, just access in Person.count directly.

这意味着,只需直接访问 Person.count 即可。

You can use closures as well, but actually in 90% cases it will be overkill. In modern browsers you also can redefine getter/setter function to wrap usage of Person.count and other "static" variables.

你也可以使用闭包,但实际上在 90% 的情况下它会过大。在现代浏览器中,您还可以重新定义 getter/setter 函数来包装 Person.count 和其他“静态”变量的使用。

This snippet demonstrates the idea:

这个片段演示了这个想法:

    function borrow(obj, borrowobj, fname) {
    obj.__defineGetter__(fname, function() {
         return borrowobj[fname]   
    })  

    obj.__defineSetter__(fname, function(val) {
             borrowobj[fname] = val      
    })
}

function Person() {
    borrow(this, Person, "count");
    this.count++
}

Person.count = 0;

new Person();
new Person();
var p = new Person();
alert(p.count);