All instances of a "class" in JS share the same prototype.
That''s why we
put methods in the prototype -- they can, and should (most of the time), be
shared. Instance variables defined in the prototype will behave more like
class-level variables, though, so always initialize them using the "
this.whatever" syntax in the class''s constructor or any other
method.
In other words, remove your three variable declarations from the prototype,
initialize them in the constructor, and you''re golden.
On 6/11/07, Jon Trelfa <jtrelfa-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:>
> When I create multiple instances of an object (created with Class.create),
> properties get copied over in whatever state they are currently in.
> Maybe I''m just not ''getting it'' ?
>
> [code]
> var testObject = Class.create();
> testObject.prototype = {
> var1:[],
> var2:{name:""},
> var3:'''',
> initialize:function(str) {
> this.var3 = str;
> },
> setVar1:function() {
> for (var i = 0, len = arguments.length; i < len; i++) {
> this.var1.push(arguments[i]);
> }
> },
> setVar2:function(str) {
> this.var2.name = str;
> }
> };
>
> //uses firebug
> function objTest() {
> var a = new testObject("McDonalds");
> a.setVar1("Abe","Lincoln");
> a.setVar2("Star Wars");
> var b = new testObject("Taco Bell");
> b.setVar1("George","Washington");
> b.setVar2("Battlestar Galactica");
> console.log(a.var1.join('' ''));
> console.log(b.var1.join('' ''));
> console.log( a.var2.name);
> console.log(b.var2.name);
> console.log(a.var3);
> console.log(b.var3);
> }
> Event.observe(window,''load'',objTest);
> [/code]
>
> When you load the page, a weird thing happens. The array contains *both*
> values for var1 and the object (var2) has been overwritten so that both
have
> a value of "Battlestar Galactica". However, var3 seems to behave
properly
> (as a result of the initialize function)
>
> Obviously, I need to use the initialize function to
''reset/set'' the
> object''s variables. I''m wondering, though, if this by
design or am I having
> a brain freeze and not understanding why it''s behaving this way?
>
> Thanks,
>
> Jon
>
>
> >
>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Spinoffs" group.
To post to this group, send email to
rubyonrails-spinoffs-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-spinoffs-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-spinoffs?hl=en
-~----------~----~----~----~------~----~------~--~---