JavaScript prototypal inheritance

Due to the use of prototypal inheritance, JavaScript is very unique in the field of popular programming languages. Let's find out what this means

Due to the use of prototypal inheritance, JavaScript is very unique in the field of popular programming languages.

Although most object-oriented languages use a class-based inheritance model, JavaScript is still based onPrototype inheritance model.

What does it mean?

Every JavaScript object has a property calledprototype, It points to another object.

This different object isObject prototype.

Our object uses the object prototype to inherit properties and methods.

Suppose you have an object created using object literal syntax:

const car = {}

Or usenew Objectsyntax:

const car = new Object()

Under any condition,carYesObject:

If you initialize an array, it is an object:

const list = []
//or
const list = new Array()

The prototype isArray.

You can pass andObject.getPrototypeOf()withObject.prototype.isPrototypeOf()method:

const car = {}
const list = []

Object.getPrototypeOf(car) === Object.prototype Object.prototype.isPrototypeOf(car)

Object.getPrototypeOf(list) === Array.prototype Array.prototype.isPrototypeOf(list)

Objects with the prototype can use all the properties and methods of the prototype:

Object.prototypeIt is the basic prototype of all objects:

Object.getPrototypeOf(Array.prototype) == Object.prototype

If you want to know what the prototype of Object.prototype is, there is no prototype:null. This is a special snowflake ❄️.

The above example you see isPrototype chainAt work.

I can create an object that extends Array and use that object to instantiate any object, which will include Array and Object in its prototype chain and inherit properties and methods from all ancestors.

In addition to usingnewOperator to create objects, or use the literal syntax of objects and arrays, you can useObject.create().

The first parameter passed is the object used as the prototype:

const car = Object.create({})
const list = Object.create(Array)

Note that because you can use instantiated arrays

const list = Object.create(Array.prototype)

under these circumstancesArray.isPrototypeOf(list)Is fake, andArray.prototype.isPrototypeOf(list)it is true.

Download mine for freeJavaScript beginner's manual


More js tutorials: