Check if Object Instance of Class

Updated on 21 May, 2025
Check if Object Instance of Class header image

Problem Statement

In this task, your objective is to implement a function checkIfInstanceOf that determines whether a given value is an instance of a specified class or any of its superclasses. This concept is rooted in object-oriented programming, where objects inherit behavior from their constructors and their prototype chains.

However, unlike JavaScript's built-in instanceof operator, your implementation must be more flexible:

  • It should work with all data types — including primitives like numbers and strings.
  • It must return false for invalid inputs, such as when the constructor is undefined or not a function.
  • It should correctly identify inherited instances across prototype chains.

This generalized approach ensures that your function can determine instance relationships reliably, even for unconventional cases that would typically fail with instanceof.

Examples

Example 1

Input:

func = () => checkIfInstanceOf(new Date(), Date)

Output:

true

Explanation:
The object returned by the Date constructor is an instance of Date.

Example 2

Input:

func = () => {
  class Animal {};
  class Dog extends Animal {};
  return checkIfInstanceOf(new Dog(), Animal);
}

Output:

true

Explanation:
Dog is a subclass of Animal. So, an instance of Dog is also an instance of Animal.

Example 3

Input:

func = () => checkIfInstanceOf(Date, Date)

Output:

false

Explanation:
A constructor function like Date is not an instance of itself.

Example 4

Input:

func = () => checkIfInstanceOf(5, Number)

Output:

true

Explanation:
Although 5 is a primitive, it can access methods from the Number prototype, like toFixed(). Thus, it's considered an instance of Number in this context.

Constraints

  • Both obj and constructor can be of any type — including undefined, null, or primitives.
  • The function must not throw exceptions for invalid types.
  • The return type is boolean.
  • You cannot use the built-in instanceof operator.

Approach and Intuition

To implement this logic, we need to replicate how JavaScript's prototype chain works, but with more inclusive input handling.

1. Validate Inputs

Before any logic runs, check if:

  • The constructor is a function — if not, return false.
  • The obj is non-null and of type "object" or "function" — otherwise, box it using Object(obj) to access its prototype.

This step ensures safety and allows handling of primitive values like numbers or strings.

2. Traverse the Prototype Chain

Use Object.getPrototypeOf() to walk up the prototype chain of the given object. At each level:

  • Compare the current prototype to constructor.prototype.
  • If a match is found, return true.
  • If the chain ends (null), return false.

This mimics the internal behavior of instanceof.

3. Handle Primitives Gracefully

Primitives like 5, 'hello', or true are not objects, but in JavaScript they can still access methods from their respective wrapper types (Number, String, Boolean). For example:

js
5..toFixed(2); // valid, due to temporary boxing

To account for this, box primitive values using Object(obj) before beginning the prototype walk.

4. Edge Case Considerations

  • checkIfInstanceOf(Date, Date) should return false — constructors are functions, not instances.
  • If either argument is undefined or null, return false safely.

Final Thoughts

This problem highlights deep understanding of JavaScript's type system and prototype chain. By abstracting away the strictness of instanceof and handling edge cases explicitly, your function will be more robust and aligned with real-world behavior.

Solutions

  • JavaScript
js
function* generatePrototypes(instance) {
  let tempPrototype = Object.getPrototypeOf(instance);
  while (tempPrototype !== null) {
    yield tempPrototype;
    tempPrototype = Object.getPrototypeOf(tempPrototype);
  }
}

var isInstanceOf = function (object, constructorFunc) {
  if (object === null || object === undefined || typeof constructorFunc !== "function")
    return false;

  for (const proto of generatePrototypes(object)) {
    if (proto === constructorFunc.prototype) return true;
  }

  return false;
};

In JavaScript, to check if an object is an instance of a particular class, you can use the custom isInstanceOf function provided in the solution. This function determines if a given object inherits from a specific constructor's prototype, which is a useful alternative to JavaScript's native instanceof operator, especially in cases that involve different contexts, such as different iframes or realms where prototypes may not match.

Here’s how the solution works:

  • Generate Prototype Sequence:

    • A generator function generatePrototypes is defined to yield each prototype in the prototype chain of the given instance, starting from the object itself up to the top of the chain (null).
  • Check Instance Against Constructor:

    • Another function, isInstanceOf, checks if the specified object is an instance of given constructor. This is done by iterating over the prototypes generated by generatePrototypes.
    • It compares each prototype in the chain with the prototype of the constructor function. If a match is found, it returns true, indicating that the object is an instance of the class.
    • The function handles edge cases where the object might be null or undefined, or if the supposed constructor is not a function, returning false in those situations.

Usage:

  • Use isInstanceOf by passing the object and the constructor function as arguments.
  • If it returns true, the object is an instance of the class represented by the constructor function.
  • If it returns false, the object is not an instance of that class.

This approach employs JavaScript ES6 features, particularly generator functions, to provide a robust check for object-instance relationships, which can be particularly useful in complex applications where inheritance checks need to cross execution contexts.

Comments

No comments yet.