⚡Flashcard Drill➔
NeetCode #968LC-2618MediumJavaScript
← Back to All Problems

#968 · #2618 · Check if Object Instance of Class(检查是否是类的对象实例)

📌 Problem Statement & Constraints

Implement checkIfInstanceOf(obj, classFunction), which determines whether obj is an instance of classFunction by walking the prototype chain. It must support primitives and Object.create(null), and return false when classFunction is not a function.

💡 Core Algorithmic Approaches

  1. Return false when obj is null or undefined, or when classFunction is not a function.
  2. Walk the prototype chain starting from Object.getPrototypeOf(obj), comparing each prototype with classFunction.prototype.
  3. Object.getPrototypeOf auto-boxes primitives, so Object.getPrototypeOf(1) is Number.prototype, making checkIfInstanceOf(1, Number) return true.
  4. Do not use instanceof: some cases such as Object.create(null) throw or behave incorrectly with it.

💻 Benchmark Python3 Implementation

var checkIfInstanceOf = function(obj, classFunction) {
    if (obj === null || obj === undefined) return false;
    if (typeof classFunction !== "function") return false;
    let proto = Object.getPrototypeOf(obj);   // primitives are auto-boxed
    while (proto !== null) {
        if (proto === classFunction.prototype) return true;
        proto = Object.getPrototypeOf(proto);
    }
    return false;
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(d): d is the prototype-chain length, usually constant.
💾 Space Complexity
O(1): constant space.

⚠️ Interview Pitfalls & Follow-ups

  • Using obj instanceof classFunction directly: it returns false for primitives and throws for Object.create(null).
  • Forgetting the classFunction type check: a non-function argument must return false rather than throw.
  • Omitting the null/undefined guard: Object.getPrototypeOf(null) throws.
  • Checking only one prototype level: the whole chain must be traversed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems