← 中文资源

简体中文版本

Symbol.hasInstance 自定义 instanceof 判断

static Symbol.hasInstance 让类自己决定 instanceof 的结果:结构匹配的对象即使没有继承关系也能通过判断,规则集中在类上一处维护,错误形态照样被拒。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

real instanceof CsvRow: true
duck instanceof CsvRow: true
wrong instanceof CsvRow: false
plain instanceof CsvRow: false

实现说明

底层就是类 CsvRow、Plain。 real、duck、wrong 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 real instanceof CsvRow:、duck instanceof CsvRow:、wrong instanceof CsvRow:——输出的每一行都能指回产生它的那次调用。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件的状态由几个模块级绑定持有:real、duck、wrong。

核心语句

return Array.isArray(value?.cells) && value.cells.every((c) => typeof c === 'string');

代码示例

// instanceof 默认走原型链;static Symbol.hasInstance 让类自定义判断规则
class CsvRow {
  constructor(cells) {
    this.cells = cells;
  }

  // 结构匹配就通过:真正解析 CSV 的库常用这种鸭子判断放宽入参
  static [Symbol.hasInstance](value) {
    return Array.isArray(value?.cells) && value.cells.every((c) => typeof c === 'string');
  }
}

const real = new CsvRow(['id', 'name']);
const duck = { cells: ['a1', 'b2'] };
const wrong = { cells: 'nope' };

console.log('real instanceof CsvRow:', real instanceof CsvRow);
console.log('duck instanceof CsvRow:', duck instanceof CsvRow);
console.log('wrong instanceof CsvRow:', wrong instanceof CsvRow);

// 普通对象没有 cells 数组:仍被拒绝
class Plain {}
console.log('plain instanceof CsvRow:', new Plain() instanceof CsvRow);