Mark As Completed Discussion

Solution

Our solution is pretty simple, it is a method that will first check the validity of the object, and then check if it is actually a prototype of the class' constructor.

If the object does not exist or we've reached the base object constructor, we will return false, since clearly it is not an instance of the given class.

JAVASCRIPT
1if(!obj || typeof obj !== 'object') return false

The second check we are going to perform is if the given parameter is a valid object, and if it is not, then we are going to throw an error.

JAVASCRIPT
1if(!target.prototype) throw Error

Finally, to check if our object is an instance of the given class, we are going to check if the object's prototype matches the class' prototype, and if it does - return true. Otherwise, we will call the method recursively to recurse down the prototypal chain, and check if the object is from a class that is extending our target class.

JAVASCRIPT
1if (Object.getPrototypeOf(obj) === target.prototype) {
2    return true
3} else {
4    return instanceOfClass(Object.getPrototypeOf(obj), target)
5}

This being said, our final solution would look like this:

JAVASCRIPT
1function instanceOfClass(obj, targetClass) {
2    if (!obj || typeof obj !== 'object') return false
3    if (!target.prototype) throw Error
4
5    if (Object.getPrototypeOf(obj) === target.prototype) {
6        return true
7    } else {
8        return instanceOfClass(Object.getPrototypeOf(obj), target)
9    }
10}