← 中文资源

简体中文版本

原型链决定 instanceof 的结果

instanceof 沿原型链匹配每个祖先类,getPrototypeOf 逐跳揭示链接,hasOwn 只看实例自身属性,继承方法依旧经由链条解析。

阅读英文原文

运行结果

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

Bike     : true
Transport: true
Object   : true
chain hop: Bike
chain hop: Transport
own props: false false
methods  : ring! started

实现说明

底层就是类 Transport、Bike。 文件的主干是一个循环——while (hop && hop.constructor.name !== 'Object')。 bike、hop 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 Transport:、chain hop:、own props:——输出的每一行都能指回产生它的那次调用。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 状态都挂在模块顶层:bike、hop。

核心语句

start() { return 'started'; }
ring() { return 'ring!'; }

代码示例

// Each class links to its parent through the prototype chain.
class Transport {
  start() { return 'started'; }
}
class Bike extends Transport {
  ring() { return 'ring!'; }
}
const bike = new Bike();

// instanceof walks the chain: every ancestor matches.
console.log('Bike     :', bike instanceof Bike);
console.log('Transport:', bike instanceof Transport);
console.log('Object   :', bike instanceof Object);

// getPrototypeOf reveals the same links one hop at a time.
let hop = Object.getPrototypeOf(bike);
while (hop && hop.constructor.name !== 'Object') {
  console.log('chain hop:', hop.constructor.name);
  hop = Object.getPrototypeOf(hop);
}

// hasOwn stays on the instance, ignoring inherited methods.
console.log('own props:', Object.hasOwn(bike, 'ring'), Object.hasOwn(bike, 'start'));

// Inherited methods resolve through the chain they belong to.
console.log('methods  :', bike.ring(), bike.start());