skip to Main Content

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


  1. You can use isPrototypeOf to avoid an explicit loop.

    return !!classFunction?.prototype && obj != null 
              && classFunction.prototype.isPrototypeOf(Object(obj));
    
    Login or Signup to reply.
  2. Unfortunately you need to traverse the prototype chain. If a while loop isn’t allowed you could use recursion:

    const isInstanceOf = (obj, constructor) => {
      if(!obj) return false;
      if(obj.__proto__ === constructor.prototype) return true;
      return isInstanceOf(obj.__proto__, constructor);
    };
    
    console.log(isInstanceOf(new RegExp, RegExp));
    console.log(isInstanceOf(new RegExp, Object));
    console.log(isInstanceOf(new RegExp, String));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search