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!

2
  • 1
    this does not look like javascript, more like php. Commented Jun 5, 2012 at 10:31
  • 3
    @Qmal This is exactly what OP says: "here is some php code, how to do the same in javascript?" Commented Jun 5, 2012 at 10:31

2 Answers 2

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";
}
Sign up to request clarification or add additional context in comments.

4 Comments

You just copied the duplicate. Vote to close instead of answering, please, it avoids unnecessary duplication.
@FlorianMargaine I started writing this before you posted your comment. You're right though, this is a duplicate.
My bad then :-) My first comment still applies though.
I would vote to close, but I don't have that privilege yet. Hopefully others can help with the vote.
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();

3 Comments

And... what does new bar() gives? It looks like OP wants a class-like solution, not how to make private/public variables.
@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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.