0
var myUser = (function () {
    var username = "",
    var isConnected = false;
    return {
        setUsername: function (n) {
            username = n;
        },
        setConn: function (connStatus) {
            isConnected = connStatus;
        },
        user: username,
        isCon: isConnected
    };
}());

When I call

myUser.setUsername("user123");

username variable does not get updated.

Any advice?

2
  • Probably just a typo, but missing a ; on the var username = "" line... Have you tried this.username = n instead, so you're setting the object's own username member, and not some random variable whose name happens to be the same? Commented Aug 13, 2012 at 2:08
  • You mean like it was defined to begin with? Commented Aug 13, 2012 at 2:11

3 Answers 3

3

It looks like you want to use myUser.user to refer the updated username value. However, if that's the case, it doesn't work. setUsername updates username variable, but myUser.user only points to username's initial value, which is "". It won't points to the updated username value

to fix the problem, you can change

user: username,

to

user: function() {
    return username;
},
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly. To the asker: please note that the connection getter and setter have to be reworked as well, according to the same logic. Also, setConn is currently introducing a global variable isConn (typo?)
Yes, sorry, that's a typo, I changed the variable names when copying pasting here.
1

This might be a better case to use prototype model:

function User(prop) {
  prop = prop || {};
  this.username = prop.username || '';
  this.isConnected = prop.isConnected || false;
}
User.prototype = {
  setUser: function(uname) { this.username = uname; },
  setConn: function(status) { this.isConnected = status; }
};

var myUser = new User();
myUser.setUser('user1234');
// OR
var myUser = new User({ username: 'user1234' });

console.log(myUser.username); //=> 'user1234' 

2 Comments

what does prop = prop || {} do?
it just makes sure that prop is not undefined. It means if there's no prop then use an empty object
0
    ....
    },
    user: username,
    isCon: isConnected

user: username forces the username to be evaluated, which returns "". This is more easy to figure out what happend

   var obj = {
        log: console.log("printed when init")
   }

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.