In the code below
function Hello(){
//
}
console.dir(Hello);
My question is:
From where and how Object comes in the prototype object of Hello ?
What is happening behind the scenes to bring Object there ?
In the code below
function Hello(){
//
}
console.dir(Hello);
My question is:
From where and how Object comes in the prototype object of Hello ?
What is happening behind the scenes to bring Object there ?
On
From where and how Object comes in the prototype object of Hello ?
It doesn't, but that console display does make it seem like that. The prototype of the object on Hello.prototype is actually Object.prototype, not Object:
function Hello() {
}
console.dir(Hello);
console.log(Hello.prototype.__proto__ === Object); // false
console.log(Hello.prototype.__proto__ === Object.prototype); // true
The console is showing Object there as the type (loosely speaking) of Hello.prototype.__proto__, not as its value.
(Note: I've used __proto__ above because that's how the console was showing it to you in your example, but I strongly recommend not using the __proto__ accessor in code. Use Object.getPrototypeOf instead.)
I think you know this, but for completeness: The reason that Hello.prototype's prototype is Object.prototype is that the prototype property of a traditional function (and class constructors) is created by the JavaScript engine when it creates the function. For traditional functions and base classes, that prototype object is created as though with an object literal: {}. So that object has Object.prototype as its prototype. (Classes using extends work slightly differently.)
Do not confuse
prototypeas property of a function with its actual prototype (accessible through__proto__/getPrototypeOf()and used in name resolution mechanism, among other things).In your example,
Hello.prototypeis used as a shared prototype for all the objects created with Constructor pattern: that is, when this function is invoked withnewoperator. And yes, this prototype is essentially an object:And that's the key idea of prototype-based object model in JS: all the things that are shared between instances are stored just once.
Note that arrow functions do not have
prototypeproperty on them (as you're not expected to use them as constructors):