如何在 javascript 类中创建一个静态数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5244710/
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-10-25 16:30:48  来源:igfitidea点击:

How to make a static array in javascript class?

javascriptarraysclassstatic

提问by Rana Ijaz

A class is made in javascript. I create its objects in differnt other scripts. But I need its one data member(array) to be static? every time I create a new object of that class then it should not lost that arrays data. I need old array data...

一个类是用javascript制作的。我在不同的其他脚本中创建它的对象。但我需要它的一个数据成员(数组)是静态的?每次我创建该类的新对象时,它都不应该丢失该数组数据。我需要旧的数组数据...

回答by johnhunter

You can simulate static members with a property on the constructor. In the example below we have a psuedo-class with a constructor Foo. When we create an instance of Foo a reference to the instance is added to Foo's static instancesproperty.

您可以使用构造函数上的属性模拟静态成员。在下面的示例中,我们有一个带有构造函数的伪类Foo。当我们创建 Foo 的实例时,对该实例的引用被添加到 Foo 的静态instances属性中。

function Foo () {
    this.description = ' this is the Foo class';
    Foo.instances.push(this); // static member keeps ref to each instance
};

// this is an instance member
Foo.prototype.getDescription = function () {
    return this.description;
}

// this is a static member
Foo.instances = [];

So what we're really talking about here is using the constructor as a 'namespace' to hold variables that are in some way related to the 'class'. Its better than using globals because its a little cleaner. As others have said, there are no classes as such but this pattern is conceptually close to static members if you like to think in a class-ical way.

所以我们在这里真正谈论的是使用构造函数作为“命名空间”来保存以某种方式与“类”相关的变量。它比使用全局变量更好,因为它更干净。正如其他人所说,没有这样的类,但如果您喜欢以经典的方式思考,这种模式在概念上接近静态成员。

回答by Jakub Konecki

Just create a global variable.

只需创建一个全局变量。

<script>
    var myGlobalArray = [];
</script>

回答by KooiInc

The trick is to create a private variable and define the prototype methods within the constructor, to be able to use the private variable in the closure.

诀窍是创建一个私有变量并在构造函数中定义原型方法,以便能够在闭包中使用私有变量。

So, this may approach what you want?

那么,这可能接近您想要的吗?

function Foo(){
  var staticArr = [];
  if (!('prototypemethodsset' in Foo)){
      var proto = Foo.prototype;
      proto.getArr = function(){
          return staticArr;
      };
      proto.addArr = function(){
           staticArr.push(Array.prototype.slice.call(arguments));
      };
      proto.prototypemethodsset = true;
  }
}

var f = new Foo
  , g = new Foo;

f.addArr(1,4,8,9,13,7);
g.addArr(5,7);
alert(g.getArr()); //=> 1,4,8,9,13,7,5,7
alert(f.getArr()); //=> 1,4,8,9,13,7,5,7