I want to use objectoriented Javascript, but the behaviour of my “object” is not as I expect them to be.
This is my object:
var Test = function(a){
var variable = a;
this.getA = function(){
return this.variable;
}
this.setA = function(a){
this.variable = a;
}
}
Now I run this code:
var a = new Test("foo");
var b = new Test("bar");
alert(a.getA()); //undefined, but "foo" expected
alert(a.getA() == b.getA()); //true, but false expected
alert(a.variable); //undefined, as expected
a.variable = "whatever";
alert(a.getA()); //"whatever", but undefined expected
alert(a.variable); //"whatever", but undefined expected
a.setA("somewhere");
alert(a.getA()); //"somewhere", as expected
alert(a.variable); //"somewhere", but undefined expected
Does anyone know how to create a functioning object, without the need to call “setA(a)” at the beginning, and with object encapsulation not allowing a.variable = “whatever”;?
If you’re encapsulating the value of
a, you don’t need to usethis.variableto access the value, simply changingthis.variabletovariableshould fix the issue.Variables have functional scope, so
var variabledefines a variable that is in scope not only forTest, but also forsetAandgetA: