- Just like people inherit genes from their parents, an object inherits its
prototype
directly from the constructor function that created it. For example, here theDog
constructor creates thebeagle
object:
function Dog(name) {
this.name = name;
}
let beagle = new Dog("Snoopy");
-
beagle
inherits itsprototype
from theDog
constructor function. You can show this relationship with theisPrototypeOf
method:
Dog.prototype.isPrototypeOf(beagle);
- This would return
true
.
Understand the Prototype Chain
- All objects in JavaScript (with a few exceptions) have a
prototype
. Also, an object’sprototype
itself is an object.
function Dog(name) {
this.name = name;
}
typeof Dog.prototype; // yields object
Because a
prototype
is an object, aprototype
can have its ownprototype
! In this case, theprototype
ofBird.prototype
isObject.prototype
:How is this useful? You may recall the
hasOwnProperty
method from a previous post:
let beagle = new Dog("Snoopy");
beagle.hasOwnProperty("name");
- The
hasOwnProperty
method is defined inObject.prototype
, which can be accessed byDog.prototype
, which can then be accessed by beagle. This is an example of theprototype
chain. In thisprototype
chain,Dog
is thesupertype
forbeagle
, whilebeagle
is thesubtype
.Object
is asupertype
for bothDog
andbeagle
.Object
is asupertype
for all objects in JavaScript. Therefore, any object can use thehasOwnProperty
method.
Top comments (0)