0

I'm having trouble getting my function to increment user id on the creation of every new object, but also preventing other functions from changing it.

function User(u_name) {
    this.user_name = u_name;
    this.user_id = User.next_user_id++;
}

User.next_user_id = 1;

user1 = new User('john');
user2 = new User('jane');

if I move next_user_id into function User as var next_user_id then it gets reset on every new object, which is not what I want. How can I increment user_id for every new object but prevent other functions from changing it?

theintellects
  • 1,320
  • 2
  • 16
  • 28

2 Answers2

4

you should try looking up closures...

var User = (function()
{
    var next_user_id = 1;
    return function(u_name) 
    {
        this.user_name = u_name;
        this.user_id = next_user_id++;
    }

})()


user1 = new User('john');
user2 = new User('jane');
Community
  • 1
  • 1
CaldasGSM
  • 3,032
  • 16
  • 26
0

You need to attach the variable to the function's prototype.

Try:

User.prototype.next_user_id = 1;

If you want to control access to (C# like) internal only, you need to turn it into a property.

var $Mynamespace$User$Count = 0;

function $Mynamespace$User$IncrementUser() { 
    $Mynamespace$User$Count++; 
};

var User = function(name){
    this.name = name;
    $Mynamespace$User$IncrementUser();
};

User.prototype = {
    GetUserCount: function() { return $Mynamespace$User$Count; }
};

var jane = new User("jane");
var john = new User("john");

alert(User.prototype.GetUserCount());
alert(jane.GetUserCount());
Nick
  • 4,002
  • 4
  • 30
  • 41
  • That's what I did originally, but can't another function modify that using by `User.prototype.next_user_id = 2;`? – theintellects Nov 16 '13 at 03:02
  • As far as an object instance is concerned, it can only change its own value. If you're worried about an internal method changing it, you need to hide the variable and return an accessor to it. – Nick Nov 16 '13 at 03:11
  • Actually, yes, someone could do that just fine by using `instance.prototype.next_user_id = "cat"`. The only way to "hide" the variable is to wrap it in a closure as per CaldasGSM's suggestion. – Mike 'Pomax' Kamermans Nov 16 '13 at 03:32