'Three different approaches to function encapsulation
I'm used to using a class to group common functions and data within a central contain. However, with javascript it seems there are multiple ways to do this, and in looking through code I see that often a non-class approach is even used quite frequency.
For example, if we take the following toy code to do some math (and allow method chaining), here are three variations I may sometimes see:
// object approach
const MathObject = {
num: undefined,
setNum(x) {this.num = x; return this;},
square(x) {this.num *= this.num; return this},
print() {console.log(this.num); ; return this},
}
let m=Object.create(MathObject);
m.setNum(2).square().print()
// Response to the comment below -- can uncomment to test
// let diff_1 = Object.create(MathObject).setNum(2).square()
// let diff_2 = Object.create(MathObject).setNum(5).square()
// diff_1.print(), diff_2.print()
// let same_1 = MathObject.setNum(2).square()
// let same_2 = MathObject.setNum(5).square()
// same_1.print(), same_2.print()
// function approach
function MathFunction() {
let num;
return {
square(x) {this.num *= this.num; return this},
setNum(x) {this.num = x; return this;},
square(x) {this.num *= this.num; return this},
print() {console.log(this.num); ; return this},
}
}
let a = MathFunction()
a.setNum(2).square().print();
// class approach
class MathClass {
num;
constructor(x) {this.num = x; /*ignored for now*/ }
setNum(x) {this.num = x; return this}
square(x) {this.num *= this.num; return this}
print() {console.log(this.num);return this;}
}
m = new MathClass();
m.setNum(2).square().print()
Is this an accurate summary of the most common ways in javascript that data and methods are encapsulated? And is there ever a reason not to use a class (other than I suppose maintaining style on an older project)?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
