Is there a way to create some type of variable that is the same in every instance of a JavaScript Class (no global variables)?
For example:
function Class(){
this.foo = 'bar';
this.setText = setText;
this.getText = getText;
}
function setText(value){
this.foo = value;
}
function getText(){
alert(this.foo);
}
Now I create two instances of the same class like so:
var fruit = new Class();
var groceries = new Class();
When I change the value of foo in the class fruit I also want it to be changed in groceries.
fruit.setText("apple");
fruit.getText(); //alerts apple
groceries.getText(); //SHOULD also alert apple
I am creating the instances of a class dynamically, they don't have a clear variable names (fruit, groceries) like in the example.
Thanks!
Is there a way to create some type of variable that is the same in every instance of a JavaScript Class (no global variables)?
For example:
function Class(){
this.foo = 'bar';
this.setText = setText;
this.getText = getText;
}
function setText(value){
this.foo = value;
}
function getText(){
alert(this.foo);
}
Now I create two instances of the same class like so:
var fruit = new Class();
var groceries = new Class();
When I change the value of foo in the class fruit I also want it to be changed in groceries.
fruit.setText("apple");
fruit.getText(); //alerts apple
groceries.getText(); //SHOULD also alert apple
I am creating the instances of a class dynamically, they don't have a clear variable names (fruit, groceries) like in the example.
Thanks!
Share Improve this question asked Feb 12, 2014 at 14:29 OodOod 1,8154 gold badges27 silver badges50 bronze badges 1- 1 possible duplicate of Static variables in JavaScript – asawyer Commented Feb 12, 2014 at 14:31
2 Answers
Reset to default 10Yes, there absolutely is, just use a property on the function itself:
Class.text = 'apple'
Class.prototype.getText = function () { return Class.text; }
Class.prototype.setText = function (text) { Class.text = text; }
An alternative approach, using a closure:
var Class = (function () {
var foo = "bar";
function Class(){
this.setText = setText;
this.getText = getText;
}
function setText(value){
foo = value;
}
function getText(){
alert(foo);
}
return Class;
}());
var fruit = new Class();
var groceries = new Class();
foo
in this case would be similar to a private static property, which is not available from the outside.