JavaScript Prototype Chain Basics

Mar 24, 2021 · 2 min read · 346 Words · -Views -Comments

The prototype chain is one of the core JS basics. After reading many articles, it is better to summarize it myself to reinforce understanding.

Key keywords: prototype, proto, constructor, new.

If there are mistakes, please correct me.

  1. prototype is a property on functions. __proto__ is a property on objects. constructor is a property on objects.

  2. An instance’s __proto__ points to the prototype object that created it. The instance prototype’s constructor points to the constructor function. The instance prototype’s __proto__ points to the next level up. If there is no other prototype, it is Object’s instance prototype.

    See the diagram below (from the web).

  1. The constructor exists in two places: the constructor in ES6 class syntax, and the object’s constructor property. ES6 class is just syntax sugar; the underlying mechanism is still the prototype chain. So the constructor is the function that creates the instance.
  2. The prototype chain refers to the chain of objects in inheritance, not functions.

Benefits of the prototype chain

It is a flexible inheritance model compared to class inheritance. For example, B.prototype = new A() allows instances of B to access A’s methods.

Quiz

Here are some questions to test understanding.

Q1

function Fn(){
    var a = 12
    this.getName = function(){
        console.log('private getName')
    }
}

Fn.prototype.getName = function (){
      console.log('public getName')
}

var fn = new Fn()
var fn1 = new Fn()
// 1, 2
console.log(fn.a)
console.log(fn.getName())
// 3, 4, 5
console.log(fn.getName === fn1.getName)
console.log(fn.__proto__.getName === fn1.__proto__.getName)
console.log(fn.__proto__.getName === Fn.prototype.getName)
// 6, 7
console.log(fn.hasOwnProperty === Object.prototype.hasOwnProperty)
console.log(fn.constructor === Fn)
/* Output
*   undefined
*   private getName
*   false
*   true
*   true
*   true
*   true
*/

Q2

function P() {}
var p1 = new P();
P.prototype.age = 18;
P.prototype = {
  constructor: P,
  name: 'zz'
};
P.prototype.num = 20;
P.prototype.age = 20;
console.log(p1.name);
console.log(p1.age, 'dd');
console.log(p1.num);
var p2 = new P();
console.log(p2.name);
/**
 * Output
 * undefined
 * 18 dd
 * undefined
 * zz
 */

Q3

function test() {}
console.log(test.prototype.constructor.constructor);
/**
 * Output
 * [Function: Function]
 */

Final Thoughts

Understanding these basic concepts is the foundation of writing good code.

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover