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.
1if(!obj || typeof obj !== 'object') return falseThe 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.
1if(!target.prototype) throw ErrorFinally, 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.
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:
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}xxxxxxxxxxfunction 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) }}