Reputation: 2507
If you try to print out the __proto__
property of a regular object, say {}.__proto__
or foo.__proto__
, you get [object object]
; this [object object]
is the prototype of another object. However, if you try to print out the __proto__
property of any function, it gives you function () { [native code] }
. Why is that ? Shouldn't it return the prototype of the object that Function
inherits from, which should be an object instead of another function (like function(){native code]}
) ? How is it possible that the __proto__
of a function is another function and not an object, like other prototypes ?
*i know that Object.getPrototypeOf(obj) should be used instead of proto, but i used that instead because it is shorter.
If someone explained the above to me, i would be grateful as well. And if you have any confusions regarding my question, please ask in the comments instead of downvoting.
Upvotes: 3
Views: 991
Reputation: 57
All the 'uppercase' constructor functions' _ proto _ will refer to Function. prototype or Function._ proto _(they refer to the same object) which is function () { [native code] } you get.
Upvotes: 0
Reputation: 18569
In JavaScript, calling a constructor function with var o = new f()
creates a new object, and
sets o.__proto__
to f.Prototype
. Same as:
new Array().__proto__ == Array.prototype // true
new Number().__proto__ == Number.prototype // true
or:
[].__proto__ == Array.prototype // true
(5).__proto__ == Number.prototype // true
Function
is a constructor function, so creating a function with new Function()
sets its prototype to Function.prototype
:
new Function().__proto__ === Function.prototype // true
or:
(function() {}).__proto__ == Function.prototype // true
All functions have this same prototype, including constructor functions. So:
Function.__proto__ == Function.prototype // true
Array.__proto__ == Function.prototype // true
Number.__proto__ == Function.prototype // true
Function.prototype
defines the default behavior of functions, that all functions inherit from, including the ability to call it, so it acts as a function itself:
Function.prototype() // undefined
(new Function())() // undefined
Upvotes: 0
Reputation: 138277
Cause
Function.prototype.toString()
will return
"function (){ [native code] }"
The Function.prototype is an object, but as you print it, its typecasted to a string, and as the prototype implements the behaviour of functions:
function(){}.toString()
it will print being a function even if it isnt.
function(){}
.__proto__ // Function.prototype
.__proto__ // Object.prototype
.toString() // "[Object object]
Maybe more imaginable:
class Human {
toString(){
return "Im a Human";
}
}
console.log(
(new Human).__proto__
);
//the Human.prototype tells you that it is a Human, however its just a class.
Upvotes: 3