Ruby Forum Rails Spinoffs > Two instances of one class use one variable

Posted by Rauan Maemirov (Guest)
on 13.05.2008 19:25
(Received via mailing list)
Hi, all.

I have class that created this way:

var MyClass = Class.create();
MyClass.prototype = {
    myVar: {},
...}

in this class i use it as this.myVar. So, when I create two instances
of this class, first instance use values from second and vice-verse.
Why? As U can see it's not singleton.
Posted by Justin Perkins (Guest)
on 13.05.2008 19:32
(Received via mailing list)
You want to setup those variables in the instance methods. The way you
have it now, it's being evaluated when the class is being created (not
instantiated) and so the variable is global to all classes.

var MyClass = Class.create({
  initialize: function(someString){
    this.myVar = someString;
  },
  whatIsMyVar: function(){ alert( this.myVar ); }
});

new MyClass('hello').whatIsMyVar();
new MyClass('world').whatIsMyVar();

-justin
Posted by kangax (Guest)
on 13.05.2008 19:45
(Received via mailing list)
Because any properties/methods outside of "initialize" are shared via
prototype chain among all instances of a class.

- kangax
Posted by Rauan Maemirov (Guest)
on 13.05.2008 19:52
(Received via mailing list)
Oh. Thanks, Justin. I didn't know that.