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
- Return false when
objisnullorundefined, or whenclassFunctionis not a function. - Walk the prototype chain starting from
Object.getPrototypeOf(obj), comparing each prototype withclassFunction.prototype. Object.getPrototypeOfauto-boxes primitives, soObject.getPrototypeOf(1)isNumber.prototype, makingcheckIfInstanceOf(1, Number)return true.- Do not use
instanceof: some cases such asObject.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 classFunctiondirectly: it returns false for primitives and throws forObject.create(null). - Forgetting the
classFunctiontype check: a non-function argument must return false rather than throw. - Omitting the
null/undefinedguard: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.