javascript - 类与原型(prototype)继承的比较

标签 javascript ecmascript-6

我试图了解当您使用 ES6 创建类的新实例时实际发生了什么。据我所知,一个新实例是用构造函数中定义的属性创建的,然后类中的其余方法实际上是原型(prototype)对象的属性

例如

class Dog {
    constructor(name){
      this.name = name
    }

    speak (){
        console.log('Woof')
    }
}

相当于

function Dog(name){
    this.name = name;
}

Dog.prototype.speak = function () {
    console.log('Woof');
}

在类示例中。如果我创建我的 Dog 类的一个实例,该方法的原型(prototype)是指向 Dog 类本身还是一个全新的对象?因为当我 Object.getPrototypeOf(myDog) 时它返回 Dog {}

最佳答案

它们在功能上完全相同。不过,这里有一些关于原型(prototype)和类的有趣属性需要指出:

class Dog1 {
    constructor(name){
      this.name = name
    }

    speak (){                    // adds speak method to the prototype of Dog1
        console.log('Woof')
    }
}

Dog1.prototype.speak = () => {    // overwrites speak method to the prototype of Dog1
 console.log('Different Woof');
}

console.log(typeof Dog1); // Class keyword is just syntactic sugar for constructor function

const newDog = new Dog1('barkie');

newDog.speak();

/////////////////////////////

function Dog2(name){
    this.name = name;
}

Dog2.prototype.speak =  () => {
    console.log('Woof');
}

const aDog = new Dog2('fluffy');

aDog.__proto__.speak();  // the __proto__ property references the prototype
aDog.speak();  // the __proto__ property is not necessary, it will automatically climb the protochain if the property is not found on the object itself.

我留下了一些评论以指出可能有点难以理解的怪癖。如果您对此有任何其他疑问,可以发表评论。希望对您有所帮助。

关于javascript - 类与原型(prototype)继承的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51824855/

相关文章:

javascript - 使用 JavaScript 函数保存表单并通过浏览器向后导航

javascript - 带有 require 的 Node.js ES6 类

jquery - es6 模块,只有几行代码。我应该导出什么?

javascript - Javascript 中的经典字数统计算法

javascript - 检查元素是否在屏幕右边缘

javascript - 在 Chrome 中,outerHeight 给出了错误的值,在 IE 和 FireFox 中则正常

javascript - 导入具有模块作为属性的对象数组在导入两次时返回未定义

javascript - 在多个文件上拆分 Javascript 类 (ES6)?

javascript - 在多个 TBODY 中更改 TR 的替代颜色

javascript - 如何使用api修改bigcommerce前端(在应用程序中添加js代码)