Js Prototype继承,Object.create有必要吗?

问题描述 投票:0回答:1
function Animal(name) {
  this.name = name;
}

Animal.prototype.printName = function() {
    console.log(`my name is ${this.name}`)
}

function Dog(name) {
    Animal.call(this, name);
    this.speak = () => console.log('woof');
}

Dog.prototype = Animal.prototype // <=== **this line here**
Dog.prototype.constructor = Dog


const leo = new Dog('leo')
leo.speak()
leo.printName()

Dog.prototype = Animal.prototype
Dog.prototype = Object.create(Animal.prototype)
有什么区别还是一样?

javascript oop prototype prototypal-inheritance
1个回答
0
投票

除了 mplungjan 的评论之外。 您可以使用更明确的

Object.setPrototypeOf()
来控制原型继承。 另外,您不需要分配 Dog 的构造函数,它已经完成了。

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

Animal.prototype.printName = function() {
    console.log(`my name is ${this.name}`)
}

function Dog(name) {
    Animal.call(this, name);
}

Dog.prototype.speak = () => console.log('woof');

Object.setPrototypeOf(Dog.prototype, Animal.prototype); 
// Dog.prototype.constructor = Dog - you don't need this, it's already done by Dog the definition
console.log(Dog.prototype.constructor);

const leo = new Dog('leo')
leo.speak()
leo.printName()

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