Reputation: 1559
If we create a function like:
function Rabbit() {}
We see that it inherits from the same object that Function
inherits from i.e.
Rabbit.__proto__ === Function.__proto__
What is this higher object? If we try to log it it looks like : ƒ () { [native code] }
. Shouldn't Rabbit
be inheriting from Function
object because it's a function? Can somebody explain where i'm wrong?
Upvotes: 1
Views: 66
Reputation: 1074335
What is this higher object?
It's the object referenced by Function.prototype
, which is also a function. It's where functions get their properties and methods from (call
, apply
, bind
, name
, and length
).
That object's prototype is the object referenced by Object.prototype
, which is responsible for basic object properties and methods such as hasOwnProperty
and toString
and, since you used it in your example, __proto__
(which is a web-only feature for backward compatibility; don't use it, use Object.getPrototypeOf
instead).
Shouldn't
Rabbit
be inheriting fromFunction
object because it's a function?
No, that's what Function.prototype
is for.
Let's put Function
, specifically, aside for a moment. Suppose you have:
function Thingy() {
}
and
let t = new Thingy();
Object.getPrototypeof(t) === Thingy.prototype
will be true, because when you use new Thingy
, the resulting object gets the object that Thingy.prototype
points to as its prototype. This is how constructor functions and prototypes work in JavaScript.
Function
is a constructor that creates functions. So the equivalent would be:
let Rabbit = new Function();
Object.getPrototypeOf(Rabbit) === Function.prototype
is true. It's also true for functions that, like your Rabbit
, aren't created via new Function
.
Upvotes: 2
Reputation: 2047
Shouldn't Rabbit be inheriting from Function object because it's a function?
No, because it is a regular function. Every function you create this way is actually a Function
object instance. See mdn.
In order to make a Function
be a prototype of your object you need to explicitly specify it as a prototype of your object and create an instance using new
keyword.
Upvotes: 1