谈到了JavaScript的继承,我们会用什么方式来实现继承呢?这里介绍了几种继承的方式(原型链继承,构造函数继承,class继承)下面来看下代码吧!
原型链继承
function Parent() {
this.age = 18
}
function Child() {
this.name = 'cc'
}
Child.prototype = new Parent()
let child = new Child()
function Animal(name) {
this.name = name;
}
Animal.prototype.getName = function() {
return this.name;
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.getBreed = function() {
return this.breed;
};
var myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.getName());
console.log(myDog.getBreed());
构造函数继承
function Animal(name) {
this.name = name;
}
function Dog(name, breed) {
Animal.call(this, name); // 使用call方法调用父类构造函数
this.breed = breed;
}
var myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.name); // 输出:Buddy
console.log(myDog instanceof Animal); // 输出:false
class继承
class F1 {
constructor() {
this.age = 18
}
}
class F2 extends F1 {
constructor() {
super()
this.name = 'cc'
}
}
let a = new F2()
class Animal {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类构造函数
this.breed = breed;
}
getBreed() {
return this.breed;
}
}
let myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.getName()); // 输出:Buddy
console.log(myDog.getBreed()); // 输出:Golden Retriever