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

129
Vistas
How to add methods dynamically to a javascript object

I have a scenario that need to add new methods to an object dynamically.

Basically, this new method will be passed as parameter to a function. Then inside the function i will add this method to the object.

sampleFunction(() => console.log("This is new function"))

function sampleFunction(newMethod) {
  var Person = {
    first_name: "Marty",
    last_name: "Mcfly",
    born: 1968,
  };

  let p = new Person();

  // code to add new methods to Person Object here ....
}

Above is the example for the scenario i faced.

Really Appreciated if anyone can help me.

Thanks.

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

0

You can't use new without a constructor. For your object literal you do not even need a class/constructor. Just attach a new property.

sampleFunction(() => console.log("This is new function"))

function sampleFunction(newMethod) {
  var Person = {
    first_name: "Marty",
    last_name: "Mcfly",
    born: 1968,
  };
Person.newMethod = newMethod;

  console.log(Person);
  Person.newMethod();
}

Note, you might want to name your method better. Suggest you to pass one more param with the name:

    sampleFunction(() => console.log("This is new function"),'mynewmethod')

    function sampleFunction(newMethod,name) {
      var Person = {
        first_name: "Marty",
        last_name: "Mcfly",
        born: 1968,
      };
    Person[name] = newMethod;

      console.log(Person);
      Person.mynewmethod();
    }

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