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

131
Visualizações
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 Respostas
Responde à pergunta

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 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