Prototypes, object prototypes, prototypal inheritance, and prototype chains in JavaScript

In JavaScript, a prototype is an object that is used to implement inheritance and shared properties between objects. JavaScript is a prototype-based programming language. Each object has a prototype, and prototypes can have their own prototypes, forming a prototype chain.

Let us explain these concepts one by one:

  1. Object prototype : Every JavaScript object (except null and undefined) has a __proto__property that references the object's prototype. You can also use Object.getPrototypeOf(obj)to get the prototype of an object. The object prototype points to the object's parent object or the prototype of the object's constructor. For example, if there is an object obj, the prototype of obj.__proto__will be referenced obj.

  2. Prototypal inheritance : Prototypal inheritance in JavaScript is achieved by pointing the prototype of an object to another object. When we access a property of an object, if the object itself does not have that property, JavaScript will look up the object's prototype chain until it finds a prototype object with the corresponding property. This achieves the effect of inheriting properties from the prototype object. If no object on the prototype chain has the property, the property's value will be undefined. Through prototypal inheritance, methods and properties can be shared, and hierarchical relationships between objects can be achieved.

  3. Prototype chain : The prototype chain is a linked list structure composed of a series of objects. Each object has a prototype, and __proto__its prototype can be accessed through properties. When we access a property on an object, JavaScript will first look in the object itself, and if not found, then go up the prototype chain until it finds the property or reaches the end of the prototype chain (null), if it has not been found yet. It returns undefined. This forms a chain of object prototypes.

Prototype, object prototype, prototype inheritance and prototype chain in JavaScript are important mechanisms for realizing object-oriented programming. Through the prototype chain, inheritance and shared properties between objects can be achieved, making the code more efficient and flexible.

Guess you like

Origin blog.csdn.net/wuzhangting/article/details/132445592