JavaScript class和继承的原理

(对于不屈不挠的人来说,没有失败这回事。——俾斯麦)

在这里插入图片描述

class

相关链接

MDN链接
有关类的详细描述
关于构造函数,原型和原型链的说明

类的概述

类是用于创建对象的模板。他们用代码封装数据以处理该数据。JS 中的类建立在原型上,但也具有某些语法和语义未与 ES5 类相似语义共享。
实际上,类是“特殊的函数”,就像你能够定义的函数表达式和函数声明一样,类语法有两个组成部分:类表达式和类声明。

JavaScript面向对象编程

在es6之前,面向对象的编程方式都是创建函数和实例化构造函数来达到目的,但这和传统的面向对象编程,比如和c++和,java的差异很大。我们先了解以下函数的面向对象编程方式

函数

创建一个普通函数animal

普通函数是可以当作函数方法来使用,直接执行业务操作后返回

const animal = function (name, color) {
    
    
  return `动物名称:${
      
      name} - 动物毛发颜色:${
      
      color}`
};
console.log(animal('刺猬', '褐色'));

创建一个构造函数Animal

构造函数是一种特殊的函数,类似传统编程的类,主要用来初始化对象,即为对象成员变量赋初始值。它总与 new 一起使用。我们可以把对象中一些公共的属性和方法抽取出来,然后封装到这个函数里面。
使用构造函数需要注意以下两点

  1. 构造函数和传统类的意义相同,首字母要大写
  2. 构造函数必须实例化才有意义,也就是new

而new的过程中也做了以下事情

  1. 在内存中创建一个新的空对象。
  2. 让 this 指向这个新的对象。
  3. 执行构造函数里面的代码,给这个新对象添加属性和方法。
  4. 返回这个新对象(所以构造函数里面不需要 return )。

构造函数的成员属性又分为静态属性和实例化属性。
实例化属性只有实例化对象后才能访问,比如hedgehogData。
静态属性不需要实例化对象就可以访问,比如height。

const Animal = function (name, color) {
    
    
  this.name = name;
  this.color = color;
  this.getAnimal = function () {
    
    
    return `动物名称:${
      
      this.name} - 动物毛发颜色:${
      
      this.color}`
  }
};
const hedgehog = new Animal('刺猬', '褐色');
const hedgehogData = hedgehog.getAnimal();
console.log(hedgehogData);
Animal.height = 50;
console.log(Animal.height);

扩展构造函数

如果后续要扩展构造函数,目前我们已经直到可以继续通过编写this.'方法名’的方式来达到目的。但这样对代码有较高的侵入性,会导致构造函数越来越臃肿,并且会导致无效的内存上涨。

const Animal = function (name, color) {
    
    
  this.name = name;
  this.color = color;
  this.getAnimal = function () {
    
    
    return `动物名称:${
      
      this.name} - 动物毛发颜色:${
      
      this.color}`
  }
};
const hedgehog = new Animal('刺猬', '褐色');
const dog = new Animal('狗', '黑色');
console.log(hedgehog.getAnimal === dog.getAnimal); // false 每个实例化对象都有自己的内存地址

但JavaScript还有原型链和原型这两个特性
关于原型和原型链的说明
我们可以通过在原型上自定义的方式进行扩展,这样就可以把成员属性定义在构造函数内,方法通过原型进行扩展。

const Animal = function (name, color) {
    
    
  this.name = name;
  this.color = color;
};
Animal.prototype.getAnimal = function () {
    
    
  return `动物名称:${
      
      this.name} - 动物毛发颜色:${
      
      this.color}`
}
const hedgehog = new Animal('刺猬', '褐色');
const dog = new Animal('狗', '黑色');
console.log(hedgehog.getAnimal === dog.getAnimal); // true 原型上的方法和属性由对象直接继承,也就是可以共享访问,所以为true 

继承

函数的继承
通过上文我们了解到,如果还想做函数的继承,那么有以下方式

  1. 继承原型
  2. 使用call方法继承
  3. 使用apply方法继承
    其步骤较为繁琐,后期维护复杂,并且和传统的面向对象编程方式不同,违背了面向对象变成的理念。

class类

基于以上问题,es6推出了class类语法糖的新规范,写法和传统面向对象类编程的方式更接近。

class Animal {
    
    
  constructor(name, color) {
    
    
    this.name = name;
    this.color = color;
  }
  getAnimal () {
    
    
    return `动物名称:${
      
      this.name} - 动物毛发颜色:${
      
      this.color}`;
  }
}
const hedgehog = new Animal('刺猬', '褐色');
const dog = new Animal('狗', '黑色');
console.log(hedgehog.getAnimal === dog.getAnimal); // true

class继承 extends

其中用到了super关键字
MDN super解释

class Animal {
    
    
  constructor(name, color) {
    
    
    this.name = name;
    this.color = color;
  }
  getAnimal () {
    
    
    return `动物名称:${
      
      this.name} - 动物毛发颜色:${
      
      this.color}`;
  }
}
class Cat extends Animal {
    
    
  constructor(name, color) {
    
    
    super();
    this.name = name;
    this.color = color;
  }
}
const dog = new Animal('狗', '黑色');
const cat = new Cat('猫', '橙色');
console.log(cat.getAnimal()); // 动物名称:猫 - 动物毛发颜色:橙色
console.log(cat.getAnimal === dog.getAnimal); // true

class编译后的结果

babel网站,可以在线编辑
我们将上面的class代码编译成nodejs原生的commonjs规范。
在这里插入图片描述

"use strict";

function _inheritsLoose(subClass, superClass) {
    
    
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
    
    
  _setPrototypeOf = Object.setPrototypeOf
    ? Object.setPrototypeOf.bind()
    : function _setPrototypeOf(o, p) {
    
    
        o.__proto__ = p;
        return o;
      };
  return _setPrototypeOf(o, p);
}
var Animal = /*#__PURE__*/ (function () {
    
    
  function Animal(name, color) {
    
    
    this.name = name;
    this.color = color;
  }
  var _proto = Animal.prototype;
  _proto.getAnimal = function getAnimal() {
    
    
    return "name:" + this.name + " - color:" + this.color;
  };
  return Animal;
})();
var Cat = /*#__PURE__*/ (function (_Animal) {
    
    
  _inheritsLoose(Cat, _Animal);
  function Cat(name, color) {
    
    
    var _this;
    _this = _Animal.call(this) || this;
    _this.name = name;
    _this.color = color;
    return _this;
  }
  return Cat;
})(Animal);
var dog = new Animal("dog", "black");
var cat = new Cat("cat", "orange");
console.log(cat.getAnimal());
console.log(cat.getAnimal === dog.getAnimal);

可以看出class只是语法糖,其类的初始化实际上就是构造函数,extends其内部也依然是原型的继承。

对比

通过原生函数和class的对比,class语法糖的写法更接近传统面向对象编程的方式,也更比原生函数容易开发,方便后期维护。

如何实现多继承

传统的面向对象编程语言都只是单继承,这是因为在大多数业务场景下通过继承能提高开发效率,提高程序性能,提高代码的复用率。但在业务复杂,项目庞大的情况下,也出现了一些缺陷

  1. 父子类之间的耦合度过高,父类的改变直接影响到子类。
  2. 子类的灵活性降低,父类中有些子类不需要或和子类冲突的属性或方法
  3. 当父类的属性或方法改变时,子类也需要更改,严重时,还需要重构子类

  4. 当然,有些业务场景下也确实需要多继承,但class是不支持多继承的,extends后只能编写一个父类。
    但我们可以通过原生原型的方式来达到多继承的目的。
function more_father () {
    
    
  this.f_name = "父亲";
  this.f_age = 55;
  this.f_address = "北京朝阳"
};

more_father.prototype.f_method = function () {
    
    
  return this.f_name + this.f_age + this.f_address;
};

function more_mother () {
    
    
  this.m_name = "母亲";
  this.m_age = 53;
  this.m_address = "北京朝阳";
};

more_mother.prototype.m_method = function () {
    
    
  return this.m_name + this.m_age + this.m_address;
};


function more_son () {
    
    
  this.s_name = "孩子";
  this.s_age = 22;
  this.s_address = "北京朝阳"
};

more_son.prototype.s_method = function () {
    
    
  return this.s_name + this.s_age + this.s_address;
};

more_son.prototype.f_pro = new more_father();
more_son.prototype.m_pro = new more_mother();
const _mores = new more_son();
console.log(_mores.f_pro.f_method());

猜你喜欢

转载自blog.csdn.net/qq_42427109/article/details/130521357