You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查函数传入参数是否为指定类的实例?

在JavaScript中检查参数是否为自定义类Person的实例

下面是几种可行的实现方式:

方法一:使用instanceof操作符(推荐)

这是最常用且可靠的方式,它会检查对象的原型链是否包含Person类的原型:

class Person {
  constructor(name) {
    this.name = name;
  }
}

function isPersonInstance(obj) {
  return obj instanceof Person;
}

// 测试示例
const validPerson = new Person('Bob');
console.log(isPersonInstance(validPerson)); // 输出: true

const plainObj = {};
console.log(isPersonInstance(plainObj)); // 输出: false

方法二:检查constructor属性

直接对比对象的constructor是否等于Person类,但这种方式有局限性——如果Person的原型被重写,或者对象来自不同的执行上下文,结果可能不准确:

function isPersonInstance(obj) {
  // 先判断obj不为null/undefined,避免报错
  return obj != null && obj.constructor === Person;
}

方法三:利用Object.prototype.toString和Symbol.toStringTag

这种方式更严谨,不受原型链修改的影响,但需要给Person类添加Symbol.toStringTag属性:

class Person {
  constructor(name) {
    this.name = name;
  }

  // 自定义toStringTag
  get [Symbol.toStringTag]() {
    return 'Person';
  }
}

function isPersonInstance(obj) {
  return Object.prototype.toString.call(obj) === '[object Person]';
}

内容的提问来源于stack exchange,提问作者Somecode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:07:01