The prototype

(1) What is a prototype

Javascript objects have a common property called a stereotype, and the property name is [proto]. The stereotype property is a reference to another object, which gives us access to all of its properties and methods.

(2)

  • When a constructor is created, the instance object inherits the constructor’s stereotype properties, which is a very important property of constructors. The constructor is instantiated in Javascript using the new keyword.
  • Each constructor has a Prototype property that points to an object, the prototype object. When an instance is created using this constructor, the prototype object pointed to by the Prototype property becomes the prototype object of the instance.
  • By default, the stereotype object has a constructor property pointing to the constructor that points to it (that is, the constructor and the stereotype object are mutually pointing).
  • In JavaScript, all objects are inherited from their prototype objects, and conversely, all objects can exist as prototype objects.

Prototype chain

(1) Prototype chain concept

All objects in JavaScript are inherited from their prototype objects. The prototype object itself is also an object, and it also has its own prototype object. In this way, a structure similar to a linked list is formed, which is the prototype chain.

(2)

  • Some corresponding methods (such as toString, valueOf, etc.) are not created when creating objects, but they can be used, because there is a prototype chain in the object. Its query mechanism is to first query whether they have this attribute, and then directly use it. If not, the property will be found in the prototype object to which Proto points.
  • Object is the parent of all objects, and all objects can be found by proto. Function is the parent of all functions, and all functions can be found by proto.
  • All prototype chains end with the Prototype property of the Object function, because objects in JavaScript are constructed by default from Object(). Prototype points to a prototype object that also has a prototype, but its prototype is null, and null has no prototype.
  • Inheritance can be implemented in JavaScript through a prototype chain. Inheritance in JavaScript is quite flexible and there are many ways to implement inheritance