js继承五大方法(原型链继承,构造函数继承,组合函数继承,寄生继承,extens继承)

157 阅读1分钟

1:原型链继承

function Father() {}
function Son() {
  this.value = 10;
}
Father.prototype.getValue = function () {
  console.log(this.value);
};
Son.prototype = new Father();
let object = new Son();
object.getValue();

此方法利用原型链的方式,将孩子的原型对象指向父类的原型对象,即可实现继承 缺点:当父类的共享数据为堆形式时,会被所有子类共享,并且无法在集成时传递参数

2:构造函数继承

function Father(a) {
  this.lin = a;
}
Father.prototype.cout = function () {
  console.log("这是父类方法");
};
function Son(a) {
  Father.call(this, a);
}
let object = new Son(3);
console.log(object.lin);//3
object.cout();//报错,查无此方法

该方法一举解决了原型链继承的两大缺点,但是会出现一个问题就是无法继承父类的原型对象上的方法

3:组合函数继承

function Father(a) {
  this.lin = a;
}
Father.prototype.cout = function () {
  console.log("这是父类方法");
};
function Son(a) {
  Father.call(this, a);
}
Son.prototype = new Father();
let object = new Son(3);
console.log(object.lin);//3
object.cout();//这是父类方法

该方法是将原型链继承和构造函数继承组合起来,解决了上述的全部问题,但缺点是进行了两次new Father的创建,造成了不必要的内存浪费

4:寄生式继承

function Father(a) {
  this.lin = a;
}
Father.prototype.cout = function () {
  console.log("这是父类方法");
};
function Son(a) {
  Father.call(this, a);
}
Son.prototype = Object.create(Father.prototype);
let object = new Son(3);
console.log(object.lin);//3
object.cout();//这是父类方法

此方法在组合式继承上的改良,将new创建对象的方法改变成Object.create的方法,此方法将Son的原型对象引向了Fathher的原型对象,减少了不必要的内存浪费

5:es6语法(extends继承)

class Father {
  nice = 10;
  callnice = function () {
    console.log(this.nice);
  };
}
class Son extends Father {}
let object = new Son();
console.log(object.nice);//10
object.callnice();//10

此方法为es6的extends新api,可以在class语法糖的基础上直接进行集成,缺点是适配性能较低