Reputation: 557
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?
Upvotes: 1
Views: 57
Reputation: 388316
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>
Upvotes: 1