LeetCode 题解工作台
检查是否是类的对象实例
请你编写一个函数,检查给定的值是否是给定类或超类的实例。 可以传递给函数的数据类型没有限制。例如,值或类可能是 undefined 。 示例 1: 输入: func = () => checkIfInstance(new Date(), Date) 输出: true 解释: 根据定义,Date 构造…
0
题型
1
代码语言
0
相关题
当前训练重点
中等 · Check if Object Instance of Class core interview pattern
答案摘要
function checkIfInstanceOf(obj: any, classFunction: any): boolean { if (classFunction === null || classFunction === undefined) {
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Check if Object Instance of Class core interview pattern 题型思路
题目描述
请你编写一个函数,检查给定的值是否是给定类或超类的实例。
可以传递给函数的数据类型没有限制。例如,值或类可能是 undefined 。
示例 1:
输入:func = () => checkIfInstance(new Date(), Date) 输出:true 解释:根据定义,Date 构造函数返回的对象是 Date 的一个实例。
示例 2:
输入:func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstance(new Dog(), Animal); }
输出:true
解释:
class Animal {};
class Dog extends Animal {};
checkIfInstanceOf(new Dog(), Animal); // true
Dog 是 Animal 的子类。因此,Dog 对象同时是 Dog 和 Animal 的实例。
示例 3:
输入:func = () => checkIfInstance(Date, Date) 输出:false 解释:日期的构造函数在逻辑上不能是其自身的实例。
示例 4:
输入:func = () => checkIfInstance(5, Number) 输出:true 解释:5 是一个 Number。注意,"instanceof" 关键字将返回 false。
解题思路
方法一
function checkIfInstanceOf(obj: any, classFunction: any): boolean {
if (classFunction === null || classFunction === undefined) {
return false;
}
while (obj !== null && obj !== undefined) {
const proto = Object.getPrototypeOf(obj);
if (proto === classFunction.prototype) {
return true;
}
obj = proto;
}
return false;
}
/**
* checkIfInstanceOf(new Date(), Date); // true
*/
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate's ability to handle inheritance and prototype chains in JavaScript.
- question_mark
Understanding of how `instanceof` works in JavaScript and potential pitfalls.
- question_mark
Ability to manage edge cases, such as undefined values or circular references in inheritance.
常见陷阱
外企场景- error
Forgetting that `instanceof` will check both the class and its parent classes, which can lead to incorrect results if not handled properly.
- error
Failing to account for edge cases where the class or the object might be undefined.
- error
Misunderstanding the difference between a class constructor and an object instance, leading to incorrect checks.
进阶变体
外企场景- arrow_right_alt
Consider whether the class check should apply only to the direct class or include all superclasses.
- arrow_right_alt
Handle cases where the object might have a custom prototype chain.
- arrow_right_alt
Explore the behavior when the provided value is an array, function, or other special object types.