Encapsulation
Any variables and functions defined inside the function body can be considered as private members. Be careful, attempts to access through the dot operator do not throw an error if the property does not exist. This will add a new property. For example, if you try to read a property, you get the value undefined.
Properties assigned to this can be considered as public members. There is a convention that names with an underscore (_) prefix mean a private member. In other words, the developer says that this member is for internal use. Although in fact, people can use it.
In ECMAScript 2015 (stage 3) any fields and methods with an sharp (#) prefix will be private member. They will be accessible only inside the object instance. Be careful, not all browsers support it.
class Rectangle {
// private fields
#width
#height
/* methods not supported yet
#area() {
return #width*#height;
}
*/
// public fields
instanceField1 = 'instance field';
instanceField2 = this.instanceField1;
constructor(width=100, height=100, x=0, y=0){
this.x=x;
this.y=x;
this.#width = width;
this.#height = height;
this.getArea = function(){ return this.#width * this.#height;}
// error, field does not defined
//this.#height1 = height;
}
}
var rect = new Rectangle(20,30);
console.log(`x=${rect.x} y=${rect.y} area = ${rect.getArea()}`);
// error, attempt to access private members
// console.log(`width=${rect.#width} area = ${rect.#area()}`);
function Rectangle(w, h, x=0, y=0){
var self = this;
var width = w;
var height = h;
function area(){return width*height;}
this.x=x;
this.y=y;
this.getArea = function(){return area();}
this.getArea1 = function(){return width*height;}
this.getPos = function(){return {x: this.x, y: this.y};}
}
var rect = new Rectangle(20,30);
console.log(`x=${rect.x} y=${rect.y} area = ${rect.getArea()}`);
// both values are undefined.
console.log(`width=${rect.width} area = ${rect.area}`);
rect.width=70;
console.log(rect);