- Just like people inherit genes from their parents, an object inherits its
prototypedirectly from the constructor function that created it. For example, here theDogconstructor creates thebeagleobject:
function Dog(name) {
this.name = name;
}
let beagle = new Dog("Snoopy");
-
beagleinherits itsprototypefrom theDogconstructor function. You can show this relationship with theisPrototypeOfmethod:
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’sprototypeitself is an object.
function Dog(name) {
this.name = name;
}
typeof Dog.prototype; // yields object
Because a
prototypeis an object, aprototypecan have its ownprototype! In this case, theprototypeofBird.prototypeisObject.prototype:How is this useful? You may recall the
hasOwnPropertymethod from a previous post:
let beagle = new Dog("Snoopy");
beagle.hasOwnProperty("name");
- The
hasOwnPropertymethod is defined inObject.prototype, which can be accessed byDog.prototype, which can then be accessed by beagle. This is an example of theprototypechain. In thisprototypechain,Dogis thesupertypeforbeagle, whilebeagleis thesubtype.Objectis asupertypefor bothDogandbeagle.Objectis asupertypefor all objects in JavaScript. Therefore, any object can use thehasOwnPropertymethod.
Top comments (0)