Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda