0

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?

1
  • User.prototype.room = new Array(), the prototype keyword here means that all of the User objects share this field. Commented May 31, 2012 at 1:50

1 Answer 1

3

You want userId and rooms to be on this, not on the prototype, or else all instances will share them.

class User
  constructor: (@userId = 0, @rooms = []) ->

u = new User 1, [1,2]
u2 = new User 2, [3,4]

alert "#{ u.userId } #{ u.rooms } #{u2.userId} #{u2.rooms}"

Try it here.

The @ simply means this..

The constructor line does a lot. It defines a constructor that

1) sets the passed values as userId and rooms on 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.