Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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)?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda