Good evening! Here's our prompt for today.
In Object-Oriented programming, an instance
represents an object
which is an instantiation of a class
. An object can also be an instance of a given class A if it is instantiated from a class B that extends the class A.
In a non-programming context, you could think of "cat" as a class and your particular cat as an instance of that class.
Many object-oriented programming languages have a built-in way of checking if a given object is an instance of a given class, and in Javascript this can be achieved by checking if the prototype
property of a constructor appears anywhere in the prototype chain of an object.
Can you implement a function that will check if an object is an instance of a class, and will accept the object and the class as parameters?
The function should work like the following example:
1class A {}
2class B extends A {}
3
4let objB = new B()
5instanceOfClass(objB , B) // true
6instanceOfClass(objB, A) // true
7
8class C {}
9instanceOfClass(objB, C) // false

Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
function instanceOfClass(obj, targetClass) {
if (!obj || typeof obj !== 'object') return false
if (!target.prototype) throw Error
if (Object.getPrototypeOf(obj) === target.prototype) {
return true
} else {
return instanceOfClass(Object.getPrototypeOf(obj), target)
}
}
Here's our guided, illustrated walk-through.
How do I use this guide?