I'm new to javascript could someone please explain why this code doesn't work?
var User = function () {
var userId = 0;
var clear = function () {
userId = 0;
}
return{
clear:clear,
userId:userId,
}
}
...
// in mocha test:
var john = new User();
john.userId = 666;
john.userId.should.equal(666); // true
john.clear()
john.userId.should.equal(0); // false
Regards
5 Answers 5
What you've done is create a function closure. This means that inside the clear function, userId is created as a local variable and is separately scoped from the global User.userId.
What you need to do is use the this keyword to specify the userId you are trying to change is the global one.
var User = function () {
var userId = 0;
var clear = function () {
this.userId = 0;
}
return{
clear:clear,
userId:userId,
}
}
5 Comments
var userId = 0; is redundant then.You are returning an object
return{
clear:clear,
userId:userId,
}
which doesn't have an id property, but userId.
You are missing the this keyword.
var User = function () {
var userId = 0;
var clear = function () {
this.userId = 0;
}
return{
clear:clear,
userId:userId,
}
}
Comments
You need to use "this" when referencing the property in the clear method
var clear = function () {
this.userId = 0;
}
Comments
There are several problems here.
1 : userId is undefined in your function definition.
2: user is undefined, so user.clear() is also undefined (actually, I'm surprised your code doen't just crash). You mean john.id and john.clear().
Userobject and assign the object reference to the variablejohn. Then you proceed to reference an undeclared variable calleduser.user.idandidwithin the constructor are two different things. One is what other languages callpublic, while the other one isprivate. They may share the name, but point towards different memory locations.