Skip to content

instanceOf

检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上

参数

参数名参数类型参数说明
targetobject检测的构造函数
ctorT extends new (...args: any[]) => void实例对象

使用

ts
import { instanceOf } from '@manzhixing/utilsxy';

class Car {
    make: string;
    model: string;
    year: number;
    constructor(make: string, model: string, year: number) {
      this.make = make;
      this.model = model;
      this.year = year;
    }
  }
  const auto = new Car('Honda', 'Accord', 1998);

instanceOf(auto, Car); // true
instanceOf(auto, Object); // true
ts
/*
 * @Author: Chengbotao
 * @Contact: https://github.com/chengbotao
 */

export function instanceOf<T extends new (...args: any[]) => void>(
  target: object,
  ctor: T
): boolean {
  let proto = Reflect.getPrototypeOf(target);
  while (proto) {
    if (proto === ctor.prototype) {
      return true;
    }
    proto = Reflect.getPrototypeOf(proto);
  }
  return false;
}