gotta have my pops
gotta have my pops

Reputation: 898

Javascript object method does not update variable

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?

Upvotes: 0

Views: 959

Answers (3)

su-
su-

Reputation: 3176

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;
},

Upvotes: 3

xiaowl
xiaowl

Reputation: 5217

    ....
    },
    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")
   }

Upvotes: 0

elclanrs
elclanrs

Reputation: 94131

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' 

Upvotes: 1

Related Questions