Monday 30 December 2019

oop - How to create a static field in javascript class




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?

Answer




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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...