Private fields in pure js (no es6)
If you use non EcmaScript6
JS version (which currently ruin in most browsers), you can do it like this:
function Human() {
var agePrivate = 0;
var self = {
agePublic: 0,
setAge: function ( a ) {
agePrivate = a;
self.agePublic = a + 1;
},
getAge: function ( ) {
return agePrivate;
},
}
return self;
}
h = Human(); // create object
h.setAge(10); // call setter
console.log("getter:", h.getAge()) // use getter
console.log("public:", h.agePublic) // use public field
console.log("private:", h.agePrivate) // will return undefined - you can't access to private field
Private methods can be implemented in same way