
Sponsored
Sponsored
In this approach, we make use of direct language features to determine if an object is an instance of a given class. Most programming languages have built-in operators or functions to check instanceof relationships, such as 'instanceof' in JavaScript, or 'isinstance' in Python.
Time Complexity: O(n), where n is the depth of prototype chain.
Space Complexity: O(1), no extra space is used.
1In Java, the 'isInstance' method from the Class class is used to determine if the input object is an instance of the specified class or its subclasses.
This approach is specifically for JavaScript where we manually traverse the prototype chain of the object to check if the class prototype is found in the chain.
Time Complexity: O(n), where n is the depth of the prototype chain.
Space Complexity: O(1)
1function checkIfInstanceOf(obj, cls) {
2 if (obj === null || obj === undefined) return false;
3 let prototype = Object.getPrototypeOf(obj);
4 while (prototype) {
5 if (prototype === cls.prototype) {
6 return true;
7 }
8 prototype = Object.getPrototypeOf(prototype);
9 }
10 return false;
11}This solution manually walks up the prototype chain by using 'Object.getPrototypeOf'. For each step in the chain, it verifies if the current prototype matches the prototype of the class, which ensures that subclass checks are also performed. This method provides finer control and understanding of the checking process.