Skip to content

回答

原型链的作用就是在当前实例上找不到某个成员(属性/方法)时,就会往它的父级查找看看有没有,如果没有在继续往上找,以此类推还是找不到就返回 undefined。 至于如何实现呢?就是将一个实例中的原型对象指向另外一个实例,另外骗一个实例的原型对象又指向了另外一个实例,最终就形成了原型链。

案例

javascript
/**
 * 世间万物
 */
function All() {}
All.prototype.die = false

/**
 * 动物类
 */
function Animal() {}
Animal.prototype = new All()
Animal.prototype.type = '动物'

/**
 * 猫类
 */
function Cat() {}
Cat.prototype = new Animal()

/**
 * 猫实例
 */
var cat1 = new Cat()

console.log(cat1.type) // 动物,因为 Cat 不存在 type,所以找到了父级的 Animal 中的 type
console.log(cat1.die) // false,因为 Cat 和 Animal 都不存在 die,所以找到了顶级的 All 中的 die
/**
 * 世间万物
 */
function All() {}
All.prototype.die = false

/**
 * 动物类
 */
function Animal() {}
Animal.prototype = new All()
Animal.prototype.type = '动物'

/**
 * 猫类
 */
function Cat() {}
Cat.prototype = new Animal()

/**
 * 猫实例
 */
var cat1 = new Cat()

console.log(cat1.type) // 动物,因为 Cat 不存在 type,所以找到了父级的 Animal 中的 type
console.log(cat1.die) // false,因为 Cat 和 Animal 都不存在 die,所以找到了顶级的 All 中的 die

更新时间: