prototypejs / prototype

Prototype JavaScript framework
http://prototypejs.org/
Other
3.53k stars 639 forks source link

Class members seem to be pointing to the same place while they shouldn't #318

Closed 0xRamsi closed 7 years ago

0xRamsi commented 8 years ago

Seems like different instance members are pointing to the same object, while they should create new ones. I actually think this behaviour could be useful. But it does not seem like something that should be happening.

Person = Class.create({
pos: {},       // Apparently a member of the class I am defining,

initialize: function(argX,argY){
this.pos.x = argX;
this.pos.y = argY;
},

getPos(){
return this.pos;
}
});
p1 = new Person(1,1);
p2 = new Person(2,2);
p1.getPosition();           // This will return {x: 2, y: 2} and not {x: 1, y: 1} as it should.

A very simple fix for that would be:

initialize: function(argX,argY){
this.pos = {};         // Adding this line
this.pos.x = argX;
this.pos.y = argY;
},
savetheclocktower commented 7 years ago

This is expected behavior, surprising though it may be. Even ES6 classes behave this way. The workaround is, as you describe, to initialize instance members in the constructor.