Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function object prototype [duplicate]

function funcObj() { } 
funcObj.prototype.greet = "hello";
console.log(funcObj.greet) // undefined ???
console.log(funcObj.prototype.greet) // hello

var obj = new funcObj();
console.log(obj.greet); // hello

As per my understanding in prototype. If you access a member of an object it will get it from prototype object when not available in that object.

My questions is:

since functions in Javascript are objects why funcObj.greet -> undefined, but obj.greet -> hello?

like image 812
Vignesh Avatar asked Nov 29 '15 13:11

Vignesh


1 Answers

A prototype is nothing more than an object from which instances inherit properties.

So, funcObj is an instance of another prototype (the one of Function) from which it has inherited all the properties. Also, it has for itself a prototype on which you can bind whatever you want and that prototype will be used once you invoke it to construct new instances of funcObj (that is, when you invoke it along with the new keywork, as new funcObj()).

Because of that, it's perfectly normal that funcObj doesn't have a member called greet, while its instances have it.

like image 113
skypjack Avatar answered Nov 15 '22 16:11

skypjack