【前端精进之路】JS篇:第12期 对象继承的6种方式

写在前面

这里是小飞侠Pan🥳,立志成为一名优秀的前端程序媛!!!

本篇文章收录于我的专栏:前端精进之路

同时收录于我的github前端笔记仓库中,持续更新中,欢迎star~

👉https://github.com/mengqiuleo/myNote


原型链继承

function Parent (age) {
  this.name = 'Parent'
  this.sex = 'boy'
  this.age = age
}
Parent.prototype.getName = function () {
  console.log(this.name)
}
function Child () {
  this.name = 'child'
}
Child.prototype = new Parent() // 实现原型链继承的精髓

Child.prototype.constructor = Child //将子类的构造函数重新指向子类,否则构造函数会丢失

var child1 = new Child()
child1.getName()
console.log(child1)

关键

子类型的原型为父类型的一个实例对象

优缺点

优点:

  • 继承了父类的模板,又继承了父类的原型对象

缺点:

  • 如果要给子类的原型上新增属性和方法,就必须放在Child.prototype = new Parent()这样的语句后面

  • 无法实现多继承(因为已经指定了原型对象了)

  • 来自原型对象的所有属性都被共享了,这样如果不小心修改了原型对象中的引用类型属性,那么所有子类创建的实例对象都会受到影响,比如下面的例子:

    function Parent () {
        this.names = ['kevin', 'daisy'];
    }
    
    function Child () {
    
    }
    
    Child.prototype = new Parent();
    
    var child1 = new Child();
    
    child1.names.push('xiaofeixia');
    
    console.log(child1.names); // ["kevin", "daisy", "xiaofeixia"]
    
    var child2 = new Child();
    
    console.log(child2.names); // ["kevin", "daisy", "xiaofeixia"]
    
  • 创建子类时,无法向父类构造函数传参数(比如上面的如果想用父类的age,但我们无法传参)

  • 某些属性其实是保存在父类型的实例对象上的;我们通过直接打印对象是看不到这个属性的


构造继承(借用构造函数继承)

function Parent (age) {
    this.names = ['a', 'f'];
    this.age = age;
}

function Child (age) {
    Parent.call(this,age);
}

var child1 = new Child(18);

child1.names.push('s');

console.log(child1.age);//18
console.log(child1.names); // ["a", "f", "s"]

var child2 = new Child();

console.log(child2.names); // ["a", "f"]

关键

在子类构造函数内部使用call或apply来调用父类构造函数

优缺点

优点:

  • 解决了原型链继承中子类实例共享父类引用对象的问题,实现多继承,创建子类实例时,可以向父类传递参数

缺点:

  • 相比原型链继承方式,父类的引用属性不会被共享,优化了第一种继承方式的弊端,但是只能继承父类的实例属性和方法,不能继承原型属性或者方法
  • 方法都在构造函数中定义,每次创建实例都会创建一遍方法(即无法实现函数复用)

组合继承

既然原型链继承构造继承都有这么多的缺点,那我们为何不阴阳结合,把它们组合在一起呢?

function Parent (name) {
    this.name = name;
    this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.getName = function () {
    console.log(this.name)
}

function Child (name, age) {

    Parent.call(this, name);
    
    this.age = age;

}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

// 测验代码

var child1 = new Child('kevin', '18');

child1.colors.push('black');

console.log(child1.name); // kevin
console.log(child1.age); // 18
console.log(child1.colors); // ["red", "blue", "green", "black"]

var child2 = new Child('daisy', '20');

console.log(child2.name); // daisy
console.log(child2.age); // 20
console.log(child2.colors); // ["red", "blue", "green"]

关键:

  • 使用原型链继承来保证子类能继承到父类原型中的属性和方法
  • 使用构造继承来保证子类能继承到父类的实例属性和方法

伪代码

// 原型链继承
Child.prototype = new Parent()
// 构造继承
function Child () {
  Parent.call(this, ...arguments)
}

优缺点

优点:

  • 可以继承父类实例属性和方法,也能够继承父类原型属性和方法
  • 弥补了原型链继承中引用属性共享的问题
  • 可传参,可复用

缺点:

  • 使用组合继承时,父类构造函数会被调用两次
  • 并且生成了两个实例,子类实例中的属性和方法会覆盖子类原型(父类实例)上的属性和方法,所以增加了不必要的内存。

解释上面的使用组合继承时,父类构造函数会被调用两次

  • 第一次是原型链继承的时候,new Parent()
  • 第二次是构造继承的时候,Parent.call()调用的

另外,我们想要继承父类构造函数里的属性和方法采用的是构造继承,也就是复制一份到子类实例对象中,而此时由于调用了new Parent(),所以Child.prototype中也会有一份一模一样的属性,可是我子类实例对象自己已经有了一份了呀,所以我怎么也用不上Child.prototype上面的了,那你这凭空多出来的属性不就占了内存浪费了吗?

当然,这两份属性我们无需担心访问出现问题,因为根据原型链的访问规则,自身有,默认一定是访问实例本身这一部分的。


寄生组合继承

组合继承的缺点是父类构造函数会被调用两次:一次使用Parent.call()来获取父类身上的属性和方法,还有一次是用new Parent()来继承父类原型上的属性和方法,但是在继承的时候我们又在子类原型Child.prototype上拿到了父类实例上的属性和方法,但是我们并不需要这些,我们真正需要的是父类原型上的属性和方法。

那么我们就需要有一种方式,使得子类的原型直接继承父类的原型,不要额外继承一些不需要的父类实例身上的属性和方法。

也就是说,我们需要一个干净的实例对象,来作为子类的原型。并且这个干净的实例对象还得能继承父类原型对象里的属性。

Object.create()

function Parent (name) {
  this.name = name
}
Parent.prototype.getName = function () {
  console.log(this.name)
}
function Child (name) {
  this.sex = 'boy'
  Parent.call(this, name)
}
// 与组合继承的区别
Child.prototype = Object.create(Parent.prototype)

var child1 = new Child('child1')

console.log(child1)
child1.getName()

原型式继承

该方法的原理是创建一个构造函数,构造函数的原型指向对象,然后调用 new 操作符创建实例,并返回这个实例,本质是一个浅拷贝。

function objcet (obj) {
    function F () {};
    F.prototype = obj;
    F.prototype.constructor = F;
    return new F();
}

ES5之后可以直接使用Object.create()方法来实现.

两个例子:

function create (obj) {
  function F () {};
  F.prototype = obj;
  F.prototype.constructor = F;
  return new F();
}
var cat = {
  heart: '❤️',
  colors: ['white', 'black']
}

var guaiguai = create(cat) 
var huaihuai = create(cat)

console.log(guaiguai)//F {}
console.log(huaihuai)//F {}

console.log(guaiguai.heart)//❤️
console.log(huaihuai.colors)//[ 'white', 'black' ]

// ES5之后
let parent4 = {
    name: "parent4",
    friends: ["p1", "p2", "p3"],
    getName: function() {
        return this.name;
    }
};

let person4 = Object.create(parent4);//借助Object.create方法实现普通对象的继承
person4.name = "tom";
person4.friends.push("jerry");

let person5 = Object.create(parent4);
person5.friends.push("lucy");

console.log(person4.name); // tom
console.log(person4.name === person4.getName()); // true
console.log(person5.name); // parent4
console.log(person4.friends); // ["p1", "p2", "p3","jerry","lucy"]
console.log(person5.friends); // ["p1", "p2", "p3","jerry","lucy"]

寄生式继承

寄生式继承就是在原型式继承的基础上再封装一层,来增强对象,之后将这个对象返回。

function createAnother (original) {
    var clone = Object.create(original); // 通过调用 Object.create() 函数创建一个新对象
    clone.fn = function () {}; // 以某种方式来增强对象
    return clone; // 返回这个对象
}

一个例子

let parent5 = {
    name: "parent5",
    friends: ["p1", "p2", "p3"],
    getName: function() {
        return this.name;
    }
};

function clone(original) {
    let clone = Object.create(original);
    clone.getFriends = function() { // 以某种方式来增强对象
        return this.friends;
    };
    return clone;
}

let person5 = clone(parent5);

console.log(person5.getName()); // parent5
console.log(person5.getFriends()); // ["p1", "p2", "p3"]

混入方式继承多个对象

混入方式继承就是教我们如何一个子类继承多个父类的。

需要用到ES6中的方法Object.assign()

它的作用就是可以把多个对象的属性和方法拷贝到目标对象中,若是存在同名属性的话,后面的会覆盖前面。(这种拷贝是一种浅拷贝)

function Child () {
    Parent.call(this)
    OtherParent.call(this)
}
Child.prototype = Object.create(Parent.prototype)
Object.assign(Child.prototype, OtherParent.prototype)
Child.prototype.constructor = Child

参考文章

💦【何不三连】做完这48道题彻底弄懂JS继承(1.7w字含辛整理-返璞归真)

  • 12
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序媛小y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值