0

I am confused, can somebody guide, in javascript, if prototype property of Function object (Function.prototype) doesn't have a prototype property then, how come a user defined function, automatically have its prototype property. like

function f(){
}
f.prototype.

Thanks

user1187405
  • 463
  • 2
  • 6
  • 17
  • All javascript functions have a prototype property. https://stackoverflow.com/questions/10812254/why-functions-prototype-is-chained-repeatedly/10812392#10812392 – Toby Hamand Jul 06 '18 at 09:38

2 Answers2

0

Almost all objects in JavaScript have the prototype property. By using it and more specifically the prototype chain we can mimic inheritance. The prototype is a reference to another object and it is used whenever JS can’t find the property you’re looking for on the current object. Simply put, whenever you call a property on an object and it doesn’t exist, JavaScript will go to the prototype object and look for it there. If it finds it it will use it, if not it will go to that object’s property and look there. This can bubble up all the way to Object.prototype before returning undefined. This is the essence of the prototype chain and the behavior that sits behind JavaScript’s inheritance.

function Animal(name) {
    this.name = name;
}

Animal.prototype.sleep = function() {
    console.log(this.name + ': Zzz...');
}

function Dog(name) {
    this.name = name;
}

// Create a reference for the prototype
Dog.prototype = Object.create(new Animal());

Dog.prototype.makeSound = function() {
    console.log(this.name + ': Woof woof!');
}

var dog = new Dog('Lassie');
dog.makeSound(); // Lassie: Woof woof!
dog.sleep(); // Lassie: Zzz...
dog.missing(); // Throws Error

Full reference:https://hackernoon.com/understanding-javascript-prototype-and-inheritance-d55a9a23bde2

NullPointer
  • 7,094
  • 5
  • 27
  • 41
0

In fact, Function object do have a prototype property, this is an excerpt from the MDN Inheritance and prototype chain:

function f() {
  return 2;
}

// Functions inherit from Function.prototype 
// (which has methods call, bind, etc.)
// f ---> Function.prototype ---> Object.prototype ---> null

For better understanding of the prototype chain, I recommend you read the following post: JS Prototype chain mechanism.

Bohao LI
  • 2,123
  • 2
  • 18
  • 24