面试中,我们往往涉及到关于 JS 继承的各方面知识,在这里,总结归纳 JS 常见的一些实现继承的方式。
构造函数的继承
绑定继承
function Animal() {
this.species = "动物";
}
function Dog(name) {
Animal.apply(this, arguments);
this.name = name;
}
let dog = new Dog("大黄");
console.log(dog.species); //动物
prototype继承
function Animal() {}
Animal.prototype.species = "动物";
function Dog(name) {
this.name = name;
}
Dog.prototype = Animal.prototype;
Dog.prototype.constructor = Dog;
var dog = new Dog("大黄");
console.log(dog.species); //动物
非构造函数的继承
关联方法(Object)
var Animal = {
species: '动物',
};
var Dog = Object.create(Animal);
console.log(Dog.species);
最常见的做法有以上几种,当然还有另外一些实现继承的方式,例如在子对象中复制父对象的属性和方法等实现继承(浅复制、深复制)。
欢迎关注,一起学习分享!