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

当我打电话

myUser.setUsername("user123");

用户名变量没有得到更新。

有什么建议吗?

4

3 回答 3

3

看起来您想使用 myUser.user 来引用更新的用户名值。但是,如果是这样,它就行不通了。setUsername 更新用户名变量,但 myUser.user 只指向用户名的初始值,即“”。它不会指向更新的用户名值

要解决问题,您可以更改

user: username,

user: function() {
    return username;
},
于 2012-08-13T02:20:59.377 回答
1

这可能是使用原型模型的更好情况:

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' 
于 2012-08-13T02:17:29.680 回答
0
    ....
    },
    user: username,
    isCon: isConnected

user: username强制username评估,返回“”。这更容易弄清楚发生了什么

   var obj = {
        log: console.log("printed when init")
   }
于 2012-08-13T02:23:41.060 回答