I’m using coffeescript to create the following class:
class User
userId: 0
rooms: new Array()
When I create a new instance of the class and add something to the array, any new instance also contains the same array. The generated javascript is:
var User;
User = (function() {
User.name = 'User';
function User() {}
User.prototype.userId = 0;
User.prototype.rooms = new Array();
return User;
})();
How do I design the class that has a new empty array every time I instantiate the class?
You want
userIdandroomsto be onthis, not on the prototype, or else all instances will share them.Try it here.
The
@simply meansthis..The constructor line does a lot. It defines a constructor that
1) sets the passed values as
userIdandroomson the object (not the prototype)2) gives a default value for each property if they are not provided.
Note I didn’t even have to do anything else in the constructor. Definitely follow the link so you can see the javascript this example creates.