JavaScript uses prototype-based inheritance, which is slightly different than inheritance in other languages. Suppose you create a new vanilla JavaScript object:

const obj = new Object();

obj instanceof Object; // true
obj.constructor === Object; // true

The instanceof operator tells you whether a given object is an instance of a given JavaScript class. You can also use instanceof with your own custom class:

class MyClass {}

const obj = new MyClass();

obj instanceof MyClass; // true
obj instanceof Object; // true

obj.constructor === MyClass; // true

The prototype Property

In JavaScript, every class has a prototype property. A class’ prototype is an object. For example, MyClass.prototype is an object:

MyClass.prototype; // MyClass {}

JavaScript has a built-in Object.getPrototypeOf() function that lets you get the prototype of an object.

const obj = new MyClass();

Object.getPrototypeOf(obj) === MyClass.prototype; // true

In JavaScript, checking if an object obj is an instance of a given class C (excluding inheritance) is equivalent to checking if Obj.getPrototypeOf(obj) === C.prototype.

#javascript #programming #developer

Understanding JavaScript's Prototype-Based Inheritance
1.60 GEEK