返回
记不住的继承方式,多种方式全在这一篇
前端
2024-01-31 15:45:55
前言
在 JavaScript 中, 重复用到的逻辑可以用函数包装起来, 在合适且需要的情况下,调用该函数即可. 而 apply, call, new 等方法也拓宽了函数的使用场景. 除了这种借来的, 我们还有继承来的. 这就是常说的原型继承. 当对象本身没有要查询的属性或方法时,JavaScript 会顺着原型链去寻找, 直到找到为止.
原型链继承
原型链继承是最常见的一种继承方式。JavaScript 中的每个对象都有一个原型对象,原型对象又指向另一个对象,如此依次向上追溯,直到指向 null 为止。
function Parent() {
this.name = '父类';
}
function Child() {
this.age = 18;
}
Child.prototype = new Parent();
const child = new Child();
console.log(child.name); // 父类
console.log(child.age); // 18
构造函数继承
构造函数继承是另一种常见的继承方式。构造函数继承通过将子类的构造函数指向父类的构造函数来实现继承。
function Parent() {
this.name = '父类';
}
function Child() {
Parent();
this.age = 18;
}
const child = new Child();
console.log(child.name); // 父类
console.log(child.age); // 18
apply 和 call 继承
apply 和 call 方法可以将一个函数的上下文指向另一个对象,从而实现继承。
function Parent() {
this.name = '父类';
}
function Child() {
Parent.apply(this);
this.age = 18;
}
const child = new Child();
console.log(child.name); // 父类
console.log(child.age); // 18
new 继承
new 运算符可以创建一个新对象,并将这个新对象的原型指向构造函数的 prototype 属性。
function Parent() {
this.name = '父类';
}
function Child() {
return new Parent();
}
const child = new Child();
console.log(child.name); // 父类
ES6 class 继承
ES6 引入了 class 语法,使得 JavaScript 中的继承更加简单。
class Parent {
constructor() {
this.name = '父类';
}
}
class Child extends Parent {
constructor() {
super();
this.age = 18;
}
}
const child = new Child();
console.log(child.name); // 父类
console.log(child.age); // 18
总结
JavaScript 中的继承方式多种多样,每种方式都有其独特的优点和缺点。在实际开发中,我们可以根据具体情况选择合适的继承方式。