W
Will
Is it possible to have private instance members in a javascript class?
function myObject() {
var private = 1;
this.getPrivate = function() {
return private;
}
this.incrementPrivate = function() {
private += 1;
}
}
var a = new myObject();
var b = new myObject();
a.incrementPrivate();
When I test the example above, calling b.getPrivate() returns 2, so it
appears that private members can only be static? I know that it is
possible to use "this.private" to achieve the intended functionality
with a public member but would prefer to make the variable "private"
inaccessible to code outside the class.
function myObject() {
var private = 1;
this.getPrivate = function() {
return private;
}
this.incrementPrivate = function() {
private += 1;
}
}
var a = new myObject();
var b = new myObject();
a.incrementPrivate();
When I test the example above, calling b.getPrivate() returns 2, so it
appears that private members can only be static? I know that it is
possible to use "this.private" to achieve the intended functionality
with a public member but would prefer to make the variable "private"
inaccessible to code outside the class.