Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!