简体   繁体   中英

How to get variables out of closure?

I have this class/service:

var User = (function () {
'use strict';

var user;

function set( user ) {
    user = user;
}

function getVotes() {
    return user.votes;
}

return {
    user     : user,
    set      : set,
    getVotes : getVotes
};

}());

I store the user like so: User.set( user ); but when i try and retrieve the user with User.user or get the users votes with User.getVotes() I get undefined. Why is that and is there a better way?

You need to use a different name for the setter methods parameter. Since you have used the name user for both the closure variable and the parameter inside the setter method when referring user it will only refer to the parameter not the closure item.

The assignment operation does not do anything as it is assigning the value of a variable to itself

 var User = (function() { 'use strict'; var user; function set(usr) { user = usr; } function getVotes() { return user.votes; } return { user: user, set: set, getVotes: getVotes }; }()); User.set({ name: 'x', votes: 5 }); snippet.log('votes: ' + User.getVotes()) 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM