更新时间:2023年12月20日10时45分 来源:传智教育 浏览次数:
在原生JavaScript中实现继承关系可以使用原型链或者ES6中的类来实现。下面笔者将分别展示这两种方式。
原型链继承通过将一个对象的原型设置为另一个对象,从而实现继承。这种方法简单,但也存在一些潜在问题。
// 父类构造函数
function Animal(name) {
this.name = name;
}
// 在父类原型上添加方法
Animal.prototype.makeSound = function() {
console.log('Some generic sound');
};
// 子类构造函数
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
// 将子类的原型设置为父类的一个实例
Dog.prototype = Object.create(Animal.prototype);
// 修正子类的构造函数指向
Dog.prototype.constructor = Dog;
// 在子类原型上添加方法
Dog.prototype.bark = function() {
console.log('Woof! Woof!');
};
// 实例化子类
const myDog = new Dog('Buddy', 'Golden Retriever');
// 测试继承方法和属性
myDog.makeSound(); // 输出: Some generic sound
myDog.bark(); // 输出: Woof! Woof!
console.log(myDog.name); // 输出: Buddy
console.log(myDog instanceof Dog); // 输出: true
console.log(myDog instanceof Animal); // 输出: true
ES6引入了class关键字,使得面向对象编程更加清晰和易于理解。
// 父类
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log('Some generic sound');
}
}
// 子类继承父类
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
console.log('Woof! Woof!');
}
}
// 实例化子类
const myDog = new Dog('Buddy', 'Golden Retriever');
// 测试继承方法和属性
myDog.makeSound(); // 输出: Some generic sound
myDog.bark(); // 输出: Woof! Woof!
console.log(myDog.name); // 输出: Buddy
console.log(myDog instanceof Dog); // 输出: true
console.log(myDog instanceof Animal); // 输出: true
这两种方式都可以实现继承关系,ES6的类语法更加清晰易懂,并且避免了原型链继承的一些问题。