JavaScript 扩展

问题描述 投票:0回答:1
function Animal() {}

function Rabbit() {}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

class Rabbit extends Animal {}

console.log(Object.getPrototypeOf(Rabbit) === Animal); 

为什么他们说这两种方式是一样的,却有这个区别

javascript
1个回答
0
投票

您提到的两种方法有一些关键区别:

  1. 函数构造函数方法
    function Animal() {}
    
    function Rabbit() {}
    Rabbit.prototype = Object.create(Animal.prototype);
    Rabbit.prototype.constructor = Rabbit;
    

在此方法中,您使用传统的函数构造函数模式定义 Animal 和 Rabbit 函数。然后,您手动将 Rabbit 的原型设置为从 Animal.prototype 创建的新对象。这就建立了原型链,其中 Rabbit.prototype 委托给 Animal.prototype。最后,将 Rabbit.prototype 的构造函数属性设置为 Rabbit,以确保它指向正确的构造函数。

  1. 类语法方法
    class Animal {}
    class Rabbit extends Animal {}
    

在此方法中,您使用 ES6 中引入的较新的类语法来定义 Animal 和 Rabbit 类。 extends 关键字用于创建继承自 Animal 的子类 Rabbit。在底层,这实现了与函数构造函数方法相同的原型链设置。

但是,在您的代码片段中,有一个错误:class Rabbit extends Animal {} 后面不应跟console.log(Object.getPrototypeOf(Rabbit) === Animal);。 Rabbit 是一个类,而不是一个实例,因此 Object.getPrototypeOf(Rabbit) 返回类构造函数的原型,而不是 Rabbit 实例的原型。

相反,要检查 Rabbit 的原型是否与 Animal.prototype 相同,您应该这样做:

console.log(Object.getPrototypeOf(Rabbit.prototype) === Animal.prototype);

这将正确记录 true,表明 Rabbit 的原型是 Animal.prototype。

© www.soinside.com 2019 - 2024. All rights reserved.