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

173
Vistas
How to nest and chain my class functions with pure JS?

How can I make such code parts work? Trying to complete task with custom HTML builder - it needs to support chaining and nesting. Understand that I need to return this, but how then to output string with HTML?

// nesting
    const template = Templater().div(
     Templater().p('Hello'),
     Templater().p('World')
    )
    console.log(template.toString())
// chaining 
console.log(Templater().br('error').toString())

example of Class that I try to create:

    class Templater {
    constructor() {}
    div(tags) {
        return `<div>${tags}</div>`
    }
    span(tags) {
        return `<span>${tags}</span>`
    } 
    br(argument) {
        if(argument) {
            return new Error('Nested content is not allowed');
        } else {
            return '<br>'
        }
    } 
    p(tags) {
        return `<p>${tags}</p>`
    } 
}

Have no idea what I need to do.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Sounds like you primarily need a custom toString method that returns the state of the tags called so far.

You'll also need to change the class to a function, because classes cannot be used without new.

const templater = () => {
  let markup = '';
  const transform = tags => tags.join('');
  return {
    div(...tags) {
      markup += `<div>${transform(tags)}</div>`
      return this;
    },
    span(...tags) {
      markup += `<span>${transform(tags)}</span>`
      return this;
    },
    br(argument) {
      if (argument) {
        throw new Error('Nested content is not allowed');
      } else {
        markup += '<br>'
        return this;
      }
    },
    p(...tags) {
      markup += `<p>${transform(tags)}</p>`
      return this;
    },
    toString() {
      return markup;
    },
  };
};

// nesting
const template = templater().div(
  templater().p('Hello'),
  templater().p('World')
)
console.log(template.toString())
console.log(templater().br('error').toString())

about 4 years ago · Juan Pablo Isaza Denunciar
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