3

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!

Ood
  • 1,445
  • 4
  • 23
  • 43
  • 1
    possible duplicate of [Static variables in JavaScript](http://stackoverflow.com/questions/1535631/static-variables-in-javascript) – asawyer Feb 12 '14 at 14:31

2 Answers2

10

Yes, 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; }
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Considering that `Class` is the `this` inside the function, why not pass `this.text`? ( unless someone's crazy enough to do a `.bind` ) – Gonçalo Vieira Feb 12 '14 at 14:33
  • 1
    @GonçaloVieira That isn't true. `this` is not `Class` inside the function, it is an object constructed from `Class`. `this.text` would not work, it would be specific to the object, not shared across all instances of the object. – user229044 Feb 12 '14 at 14:34
  • @meagar you're right, didn't see it wasn't a `Class.prototype.text`, my bad! – Gonçalo Vieira Feb 12 '14 at 14:47
1

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.

basilikum
  • 10,378
  • 5
  • 45
  • 58
  • 1
    This has the downside of being notably more expensive; each time you construct a class, that class gets its own unique set of methods, involving extra processing time and memory for each instance. – user229044 Feb 12 '14 at 15:07
  • @meagar I just copied the code from OP. He had his class constructed that way. Sure, he should use `prototype`, but that was not the question. So I thought I stick to the essential part, which is the question about static properties. – basilikum Feb 12 '14 at 16:00