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

115
Visualizações
My class will return undefined if I call its method

what I'm trying to do is a class that creates an object, appends other objects and adds content to it without having to write several lines of

var obj = document.createElement('input');
obj.value = 'this value';
obj.appendChild(anotherObject)

here is the code:

class gerarNode{
    constructor(input){
        this.nodetype = input;
        this.node = document.createElement(input);
    }
    toAppend(appends){
        this.node.appendChild(appends);
    }
}

what I expect in the browser console:

var jorge = new gerarNode('div').toAppend(anotherNodeObject)
// Object {"nodetype": "div", etc, etc}

what I get:

var jorge = new gerarNode('div').toAppend(anotherNodeObject)
// undefined

but the weirdest is, if I call only the constructor method, it will return a "div" object just as I wanted, it just not works if I call any method in the class

var jorge = new gerarNode('div')
// Object {"nodetype": "div"}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you don't execute a return statement in a function, it returns undefined.

To implement a fluent interface, all the modification functions should return this.

class gerarNode {
  constructor(input) {
    this.nodetype = input;
    this.node = document.createElement(input);
  }
  toAppend(appends) {
    this.node.appendChild(appends);
    return this;
  }
}

let anotherNodeObject = document.createElement("div");
var jorge = new gerarNode('div').toAppend(anotherNodeObject);

console.log(jorge);

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