In Javascript, the operator instanceof is used to perform a test to check if the prototype property of a constructor apperas in the chain of the object’s prototype chain.
The syntax to use is:
object instanceof constructor
// object - the object to test
// constructor - to test against
For example:
function Car() {}
function Train() {}
const car = new Car();
const train = new Train();
console.log(car instanceof Car); // true
console.log(car instanceof Train); // false
console.log(train instanceof Car); // false;
console.log(train instanceof Train); // true;
We can implement a instanceOf function in pure Javascript that does the same instanceof check – probably useful in front-end Javascript interview:
function instanceOf(left, right) {
let proto = left.__proto__;
let prototype = right.prototype;
for (;;) {
if (proto === null) return false;
if (proto === prototype) return true;
proto = proto.__proto__; // trace way up along the chain
}
}
And it expects to produce the same results:
console.log(instanceOf(car, Car)); // true
console.log(instanceOf(car, Train)); // false
console.log(instanceOf(train, Car)); // false;
console.log(instanceOf(train, Train)); // true;
The idea is conduct a loop, and trace up the prototype property along the chain until we have a match (equal prototype in the chain) or we have reached the end of the chain – which is null.
–EOF (The Ultimate Computing & Technology Blog) —
302 wordsLast Post: How to Compute the Surface Area of 3D Shapes (Cubes Placed on Grid Cells)?
Next Post: How to Find Positive Integer Solution for a Given Equation using Bruteforce, Two Pointer or Binary Search Algorithms?
