Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
0xRamsi opened this issue Jul 11, 2016 · 1 comment
Closed

Comments

@0xRamsi
Copy link

0xRamsi commented Jul 11, 2016

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
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants