Encapsulation (JavaScript)
Private Fields and Methods
Encapsulation means that the data is bundled and the methods that act on this data would imply that access to that data is restricted from outside the bundle, or in this case, their fields and methods.
Fields are split into two;
- Public Fields
- Private Fields
An example is given below;
class Halo {
currentDeveloper;
#username;
#password;
#weapons = [];
constructor(currentDeveloper, username, password) {
this.currentDeveloper = currentDeveloper;
this.#username = username;
this.#password = password;
}
};
Public Fields are written without any declaration in front of it, whereas Protected Fields are written with a ‘#’ in front of the variable. This is used to protect the variable. We can also set it to private by adding an ‘_’ in front of the variable. This will let the user know that this property should not be touched.
Methods are split into three;
- Public Methods
- Private Methods
- Static Methods
The same goes for Methods as it goes for Fields. Using either the ‘#’ or ‘_’ in front of the method will showcase that this method is Protected or Private.
class Halo {
currentDeveloper;
#username;
#password;
#weapons = [];
#gameTypes = [];
constructor(currentDeveloper, username, password) {
this.currentDeveloper = currentDeveloper;
this.#username = username;
this.#password = password;
}
getWeapons() {
return this.#weapons;
}
addWeapons(weapon) {
this.#weapons.push(weapon);
return this;
}
static helperMethod() {
console.log(‘This is a Static Method’);
}
addGameType(gameType) {
this.#gameTypes.push(gameType);
return this;
}
requestNewGameType(gameType) {
if (this.#approveNewGameType(gameType)) {
this.addGameType(gameType);
console.log(‘Game Type added!’);
}
return this;
}
#approveNewGameType(gameType) {
return true;
}
}
const halo3 = new Halo(‘Bungie Inc.’, ‘Spartan’, ‘Spartan117’);
console.log(halo3);
halo3.addWeapons(‘Sniper Rifle’);
halo3.addWeapons(‘Rocket Launcher’);
console.log(halo3);
Halo.helperMethod();
halo3.requestNewGameType(‘Forge’);
console.log(halo3);
However, when using a Protected Method, the current browser does not seem to support that code, for the Approve new Game Type Function. It will throw an error instead;
halo3.approveNewGameType(‘Multiplayer’);
console.log(halo3);
Or if you use the ‘#’ in front of it;
halo3.#approveNewGameType(‘Multiplayer’);
console.log(halo3);
This is due to the fact that the browser does not support this code.
Chaining Methods
We can use the code above to chain methods to write code more efficiently. A simple example is given below;
halo3.addGameType(‘Multiplayer’)
.addWeapons(‘Beam Rifle’)
.addWeapons(‘Battle Rifle’)
.addGameType(‘Forge’);
console.log(halo3);
However, when we chain methods, we need to return the “this” keyword in those Methods. Otherwise, an error will throw stating the property is undefined;
With the “this” keyword preserved in the methods, the methods will be chainable;