// main.js —— 原型链查找全过程 // 链:dog 实例 → Dog.prototype → Animal.prototype → Object.prototype → null function Animal(name) { this.name = name; } Animal.prototype.speak = function () { return `${this.name} makes a sound`; }; function Dog(name) { Animal.call(this, name); } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.speak = function () { return `${this.name} barks`; }; export function makeDog() { return new Dog('Rex'); } export function labelsFor(dog) { return new Map([ [dog, 'dog 实例'], [Dog.prototype, 'Dog.prototype'], [Animal.prototype, 'Animal.prototype'], [Object.prototype, 'Object.prototype'], ]); } // 从 obj 开始沿原型链查找 key,返回命中的位置与走过的路径。 export function lookup(obj, key, labels = new Map()) { const path = []; let cur = obj; while (cur !== null) { const label = labels.get(cur) || '(anonymous)'; if (Object.hasOwn(cur, key)) return { found: true, owner: label, path, value: cur[key] }; path.push(label); cur = Object.getPrototypeOf(cur); } return { found: false, owner: null, path, value: undefined }; } export function chain(dog) { const labels = labelsFor(dog); const result = []; let cur = Object.getPrototypeOf(dog); while (cur !== null) { result.push(labels.get(cur) || '(anonymous)'); cur = Object.getPrototypeOf(cur); } result.push('null'); return result; } export function run(log = console.log) { const dog = makeDog(); const labels = labelsFor(dog); const speak = lookup(dog, 'speak', labels); const name = lookup(dog, 'name', labels); const toString = lookup(dog, 'toString', labels); const missing = lookup(dog, 'fly', labels); const rows = [ ['原型链', chain(dog).join(' → ')], ['name 的归属', `${name.owner}(own)`], ['speak 的归属', speak.owner], ['toString 的归属', toString.owner], ['fly 是否找到', String(missing.found)], ["'speak' in dog", String('speak' in dog)], ['Object.hasOwn(dog, "speak")', String(Object.hasOwn(dog, 'speak'))], ['dog.constructor 指向', dog.constructor === Dog ? 'Dog' : '其他'], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:属性查找从实例开始沿 [[Prototype]] 向上,找到即停;toString 最终落在 Object.prototype。'); return rows; }