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

134
Visualizações
Unable to fetch property from prototype of function that returns function

Greet is a simple function that returns a function as an output.

We added dev to the prototype of the greet function to show developer's name.

function greet() {
    function hello(name) {
        console.log(`Hello ${name}`);
    }
    return {hello}
}

greet.prototype.dev = "Dev name";

let greetObj = new greet();

console.log(greetObj.dev) // Displays as undefined.

My expectation was that greetObj.dev or any other object created from the greet function will display the dev property defined in the greet prototype but instead we are getting undefined.

Can anyone please help where I am going wrong here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You only have to assign the value to this in constructor function. You don't have to return anything. JS will return an object will all property assign to that object

function greet() {
  function hello(name) {
    console.log(`Hello ${name}`);
  }
  this.hello = hello;
}

greet.prototype.dev = "Dev name";

let greetObj = new greet();
console.log(greetObj.dev);

Best Practice

But this is not a best practice to attach a function in the constructor function. It will just add hello function to all objects which unnecessarily create multiple copy per object, which you shouldn't do that.

You should ideally attach that function to its prototype as:

function greet() {}

function hello(name) {
  console.log(`Hello ${name}`);
}

greet.prototype.hello = hello;
greet.prototype.dev = "Dev name";

let greetObj = new greet();
console.log(greetObj.dev);
greetObj.hello("developer");

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