DEV Community

Randy Rivera
Randy Rivera

Posted on

Understanding Where an Object’s Prototype Comes From

  • Just like people inherit genes from their parents, an object inherits its prototype directly from the constructor function that created it. For example, here the Dog constructor creates the beagle object:
function Dog(name) {
  this.name = name;
}

let beagle = new Dog("Snoopy");
Enter fullscreen mode Exit fullscreen mode
  • beagle inherits its prototype from the Dog constructor function. You can show this relationship with the isPrototypeOf method:
Dog.prototype.isPrototypeOf(beagle);
Enter fullscreen mode Exit fullscreen mode
  • This would return true.

Understand the Prototype Chain

  • All objects in JavaScript (with a few exceptions) have a prototype. Also, an object’s prototype itself is an object.
function Dog(name) {
  this.name = name;
}

typeof Dog.prototype; // yields object
Enter fullscreen mode Exit fullscreen mode
  • Because a prototype is an object, a prototype can have its own prototype! In this case, the prototype of Bird.prototype is Object.prototype:

  • How is this useful? You may recall the hasOwnProperty method from a previous post:

let beagle = new Dog("Snoopy");
beagle.hasOwnProperty("name");
Enter fullscreen mode Exit fullscreen mode
  • The hasOwnProperty method is defined in Object.prototype, which can be accessed by Dog.prototype, which can then be accessed by beagle. This is an example of the prototype chain. In this prototype chain, Dog is the supertype for beagle, while beagle is the subtype. Object is a supertype for both Dog and beagle. Object is a supertype for all objects in JavaScript. Therefore, any object can use the hasOwnProperty method.

Top comments (0)