我试图了解当您使用 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/