Prototype class-instances sharing properties

3 views
Skip to first unread message

Luke

unread,
Dec 4, 2010, 10:01:52 AM12/4/10
to Prototype & script.aculo.us
Hi,

I've got a weird behavior here, or rather a behavior I don't
understand. If you take the following Class:

---
var SomeClass = Class.create({

rbBuffer: nulll,

setBuffer: function(val) {
this.rbBuffer = val;
},

getBuffer: function() {
return this.rbBuffer;
}
});
---

and play around a little bit:

---
var c1 = new SomeClass();
var c2 = new SomeClass();

c1.setBuffer(true);
c2.setBuffer(false);

log(c1.getBuffer()); // PRINTS TRUE
log(c2.getBuffer()); // PRINTS FALSE
---

everything works as expected. But if you alter that class and make
rbBuffer a JSON-object and try to set/get properties of that object,
it kinda gets shared:

---
var SomeClass = Class.create({

rbBuffer: {},

setBuffer: function(val) {
this.rbBuffer.test = val;
},

getBuffer: function() {
return this.rbBuffer.test;
}
});

var c1 = new SomeClass();
var c2 = new SomeClass();

c1.setBuffer(true);
c2.setBuffer(false);

log(c1.getBuffer()); // PRINTS FALSE
log(c2.getBuffer()); // PRINTS FALSE
---

rbBuffer.test of the first object is overwritten with the value you
set on the second object, as if the use the same variable.

Does anyone know why this is, and how to work with it?

Thanks
Lukas

yuval dagan

unread,
Dec 4, 2010, 2:44:50 PM12/4/10
to prototype-s...@googlegroups.com
Hi
 
currently the rdBuff is shared between all instatces
try to create the instance variable (here rdBuff) inside the initialize function
and with the this keyword its not default  like in C++ etc...
 
 
var SomeClass = Class.create({
 initialize: function(name) {
    this.rbBuffer = {};
  },

 

 setBuffer: function(val) {
   this.rbBuffer.test = val;
 },

.
.
.
 
 
hope it helped
 
cheers
 
yuval

--
You received this message because you are subscribed to the Google Groups "Prototype & script.aculo.us" group.
To post to this group, send email to prototype-s...@googlegroups.com.
To unsubscribe from this group, send email to prototype-scripta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/prototype-scriptaculous?hl=en.


Luke

unread,
Dec 7, 2010, 3:42:00 AM12/7/10
to Prototype & script.aculo.us
Will try that, thank you yuval
> > prototype-scripta...@googlegroups.com<prototype-scriptaculou s%2Bunsu...@googlegroups.com>
> > .
Reply all
Reply to author
Forward
0 new messages