javascriptprototype

Using prototypes to check whether an object is an instance of a class


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

Solution

  • Unfortunately you need to traverse the prototype chain if you don't want to use JS specific tools like instanceof and Object::isPrototypeOf(). If a while loop isn't allowed you could use recursion:

    const checkIfInstanceOf = (obj, classFunction) => {
      if(obj === null || obj === undefined || !classFunction?.prototype) return false;
      const proto = Object.getPrototypeOf(obj);
      return proto === classFunction.prototype || checkIfInstanceOf(proto, classFunction);
    };
    
    console.log(checkIfInstanceOf(new RegExp, RegExp));
    console.log(checkIfInstanceOf(new RegExp, Object));
    console.log(checkIfInstanceOf('', String));
    console.log(checkIfInstanceOf());