Symbol hasInstance Customizes instanceof

static Symbol.hasInstance lets a class decide what instanceof returns, so duck-typed objects matching the expected shape pass without inheriting.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the snippet

Symbol hasInstance Customizes instanceof reduces to the classes CsvRow and Plain.

Module-level bindings hold the data — real, duck, wrong — with no function scope in between.

Using it

Running the file prints labeled results such as real instanceof CsvRow:, duck instanceof CsvRow:, wrong instanceof CsvRow: — each operation’s effect is visible in the output.

Key statements

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

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `real`, `duck`, `wrong`.