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?
2

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.