var
is a function-scoped variable declaration and is therefore inaccessible outside of its function (in this case, the myClass
function). Two approaches to your problem would be either making the variable public by using this.privateVariable = 1
or using a closure with access to the variable. Here's a simple example of the latter:
function MyClass(){
var privateVar = 1;
this.incrementPrivateVar = function(){
return privateVar++;
}
}
var instance = new MyClass();
instance.incrementPrivateVar();
incrementPrivateVar()
also returns the value of the private variable, but that can be prevented by simply removing return
from that function.
If you're using ES6, there is a new, better way of creating and accessing private data that is essentially bulletproof: WeakMap
. This is the example above in ES6:
let privateData = new WeakMap();
class MyClass {
constructor(data) {
privateData.set(this, data);
}
getData() {
return privateData.get(this);
}
}
let instance = new MyClass({
data1: 1,
data2: 2
});
instance.getData();
Although you can inspect the contents of privateData
in the console, within the script, you need to have the correct, specific instance of MyClass
to access the data in privateData
. To prevent anyone from having access to what's in privateData
, you could simply wrap the let instance = ...
in a block, preventing access to the instance
variable, and therefore, the contents of privateData
.