I tried to solve the 2618s problem in LeetCode https://leetcode.com/problems/check-if-object-instance-of-class/description/ and wanted to know if there is a way to resolve it using only properties like prototype, proto and constructor, without a while loop and instanceof?
Theres a bunch of examples I tried but nothing works
return obj.constructor.prototype === classFunction.prototype
if (classFunction === Number || classFunction === String || classFunction === Date) {
return obj.__proto__ === classFunction.prototype
} else return obj.__proto__.constructor.__proto__.prototype === classFunction.prototype
2
Answers
You can use
isPrototypeOf
to avoid an explicit loop.Unfortunately you need to traverse the prototype chain. If a
while
loop isn’t allowed you could use recursion: