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

140
Vistas
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 Respuestas
Responde la pregunta

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