0

I can define a class in JavaScript like this:

var appender = function (elements, func) {
    this.Prop = something;
    staticProp = something_else;
};

Am I right? Well then, how can I create a static field in this class? And how can I access that field inside the class? I mean I want a field that be shared between all instances from the class.

var ap1 = new appender();
var ap2 = new appender();
ap1.Prop = something1;
ap2.Prop = something2;
var t = ap1.Prop == ap2.Prop; // true
ap1.staticProp = something_static;
var s = ap2.staticProp = something_static; // I want to this returns true. how can I?
amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • You can take a look at this post : [http://stackoverflow.com/questions/1535631/static-variables-in-javascript] (http://stackoverflow.com/questions/1535...) `appender.staticProp = x ;` will solve your problem. – Mehdi Karamosly Dec 07 '12 at 23:18
  • [Static variables in JavaScript](http://stackoverflow.com/questions/1535631/static-variables-in-javascript) – Rakesh Menon Dec 07 '12 at 23:27

2 Answers2

6

This is not answered so easily. It won't behave like a static var you know from other languages such as Java etc.

What you can do is append it to the function, like such:

appender.staticProp = 3

That means that within the function you have to reference it using the Function name:

var Person = function(name) {
   this.name = name;

   this.say = function() {
       console.log( Person.staticVar );
   }
}

Person.staticVar = 3;

So it allows you to append variables that are somewhat static. But you can only reference them as shown above.

Mathias
  • 2,484
  • 1
  • 19
  • 17
1

See the comments:

var appender = function (elements, func) {
    this.Prop = something; // member variable, ok
    staticProp = something_else; // global var (no var keyword!)
};

Try this:

var appender = function (elements, func) {
    this.Prop = something;

};
appender.staticProp = something_else; // static member
David Rettenbacher
  • 5,088
  • 2
  • 36
  • 45