实现说明
底层就是类 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());