Home > OS >  Unable to fetch property from prototype of function that returns function
Unable to fetch property from prototype of function that returns function

Time:12-01

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.
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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?

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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");
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related