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

160
Visualizações
Classes: methods not intrinsically related to an object vs functions

I'm new to JavaScript, currently learning classes.

I made a simple class that creates a square with a random size and color:

class Square {
  constructor(maxSize = 150, minSize = 50) {
    this.maxSize = maxSize;
    this.minSize = minSize;
    this.size = this.setRandomSize();
    this.color = this.randomColor();
  }

  createShape() {
    const square = document.createElement('div');
    square.classList.add('square');
    document.body.appendChild(square);

    square.style.cssText = `
      width: ${this.size}px;
      height: ${this.size}px;
      background-color: ${this.color};
    `;
  }

  randomNumber(max, min = 0) {
    return Math.floor(Math.random() * (max - min) + min);
  }

  setRandomSize() {
    return this.randomNumber(this.maxSize, this.minSize);
  }

  randomColor() {
    return `hsla(${this.randomNumber(360)}, 50%, 40%, .7)`;
  }
}

new Square().createShape();

As you can see in the code above, I've a 2 methods randomNumber and setRandomColor that don't use any instance or method properties.

I'm wondering what is the recommended approach or benefits (apart from portability) between having these functions inside or outside the class (as showed below). In other words, is it recommended to keep inside the class methods that are intrinsically related to the object only (code block 2) or methods that allow the class to work as a "stand alone" (code block 1)?

class Square {
  constructor(maxSize = 150, minSize = 50) {
    this.maxSize = maxSize;
    this.minSize = minSize;
    this.size = this.setRandomSize();
    this.color = randomColor();
  }

  createShape() {
    const square = document.createElement('div');
    square.classList.add('square');
    document.body.appendChild(square);

    square.style.cssText = `
      width: ${this.size}px;
      height: ${this.size}px;
      background-color: ${this.color};
    `;
  }

  setRandomSize() {
    return randomNumber(this.maxSize, this.minSize);
  }
}

function randomNumber(max, min = 0) {
  return Math.floor(Math.random() * (max - min) + min);
}

function randomColor() {
  return `hsla(${randomNumber(360)}, 50%, 40%, .7)`;
}

new Square().createShape();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I have had similar confusion when I started to learn programming. Since it is class, I would like to highlight SOLID here.

Single Responsible : A class should do one thing. Does your class's job is creating random number? You created the class because you wanted a Square, not a random size generator.

Also, if you put the functions outside of the class and use it there, your class will be coupled with those functions. What will you do if you need use rgb color instead of hsla? Another class? So less coupling will increase your class's quality.

So how I would write the class?

class Square {
    constructor(size, color){
        this.size = size;
        this.color = color;
        this.square = document.createElement('div');
        this.square.classList.add('square');
        document.body.appendChild(this.square);
    
        this.square.style.cssText = `
          width: ${this.size}px;
          height: ${this.size}px;
          background-color: ${this.color};
        `;
    }
}


function randomNumber(max, min = 0) {
    return Math.floor(Math.random() * (max - min) + min);
}
  
function randomColor() {
    return `hsla(${randomNumber(360)}, 50%, 40%, .7)`;
}

const size = randomNumber(100, 50)
const color = randomColor()
const mySquare = new Square(size, color)
about 4 years ago · Juan Pablo Isaza Relatório
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