To make this question clear, we should focus on the following aspects:

  • What is a prototype object
  • Constructors, prototype objects, triangulation of instances
  • How is the prototype chain formed

A prototype object

In JavaScript, except for a few built-in functions, most functions contain a property called prototype that points to the prototype object,

All instances created based on the constructor share access to properties of the prototype object.

For example, our hasOwnProperty, toString methods, etc. are methods of Obejct prototype objects, which can be used by any object as its own method.

HasOwnProperty is used to determine if a property is its own.

Take a look at this code:

let person = { 
  name: "Tom", 
  age: 18, 
  job: "student"
}

console.log(person.hasOwnProperty("name")) // true 
console.log(person.hasOwnProperty("hasOwnProperty")) // false 
console.log(Object.prototype.hasOwnProperty("hasOwnProperty")) // true
Copy the code

As you can see, hasOwnProperty is not a property of the Person object, but person can call it.

So how does the Person Object find hasOwnProperty in the Object prototype? It’s up to the prototype chain to do that.

Requirement: simple drawing prototype triangle diagram!

Prototype chain

In JavaScript, every object has a __proto__ attribute that points to the prototype of the current object’s constructor.

An object can be connected to the prototype object of its constructor via its own __proto__ property,

And since its prototype object also has a __proto__, this is connected to form a chain structure, which we call the prototype chain.