One Pager Cheat Sheet
- You can implement a function that will check if an object is an instance of a class, taking an object and a class as parameters, and checking if the
prototype
property of the constructor appears anywhere in the prototype chain of the given object. - We are writing a
function
to check if anobject
is an instance of agiven class
, by first checking its validity and then checking if it is a prototype of the class' constructor, and if not, recursing down the prototypal chain to check it.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
10
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)
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.