2

Possible Duplicate:
Static variables in JavaScript

How can i make a static encapsulation with self members in javascript? such as in php:

class bar{
      static public $foo;
      static public function set() {
            self::$foo = 'a';
      }
}
bar::set();

In javascript: var bar = function () { ???????? } bar.set();

Thanks!

Community
  • 1
  • 1
Gábor Varga
  • 840
  • 5
  • 15
  • 25

2 Answers2

2

Simply define them as properties of bar.

bar.foo = null;
bar.set = function() {
    bar.foo = "a";
}

Here's a nice overview:

var bar = function() {
    // Private instance variables
    var a = 1;
    // Public instance variables
    this.b = 5;
    // Privileged instance methods
    this.c = function() {
        return a;
    }
};
// Public instance methods
bar.prototype.d = function() {
    return ++this.b;
}

// Public static variables
bar.foo = null;
// Public static methods
bar.set = function() {
    bar.foo = "a";
}
Mattias Buelens
  • 19,609
  • 4
  • 45
  • 51
0

Make a closure that creates the object and returns it. Inside the closure you can declare local variables, and they are private to the scope:

var bar = (function(){

  var foo;

  return {
    set: function(){
      foo = 'a';
    }
  };

})();

bar.set();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • And... what does `new bar()` gives? It looks like OP wants a class-like solution, not how to make private/public variables. – Florian Margaine Jun 05 '12 at 10:39
  • @FlorianMargaine: Aaaaannd... Nothing obviously, as `bar` is not a function. The usage in the question shows that the OP wants something that can be used as an object, what suggests that it should also work as a constructor? – Guffa Jun 05 '12 at 10:44
  • Well, it's what the "static" term usually means: use a static method defined in a class you can instantiate. I guess your answer has its place, though. – Florian Margaine Jun 05 '12 at 10:47