JavaScript继承

113 阅读2分钟

继承

原型链实现继承

原型链实现继承就是将A的原型指向B的实例,这样A就继承了B,A的实例就可以访问到B自身属性以及原型对象的属性。

image.png

(function () {
  function A () { }
  A.prototype.getNowDate = function () {
    console.log('getNowDate');
    return new Date().toLocaleString()
  }
  function B () {
​
  }
  B.prototype = new A()
  let b = new B();
  console.log(b, b.getNowDate());
})()

image.png 根据原型链的查找规则,当调用getNowDate函数时,查找规则如下

image.png 缺点:

1.原型链上属性为所有实例共享,一个实例修改其他实例属性也随之改变,不适合一些各个实例的私有属性

构造函数继承

(function () {
  function A (seconds) {
    this.TimeStr = new Date(seconds).toLocaleString()
  }
  //获取当前时间
  A.prototype.getNowDate = function () {
    console.log('getNowDate');
    return new Date().toLocaleString()
  }
  A.prototype.getTime = function () {
    return this.TimeStr
  }
  let a = new A();
  // console.log(a.getTime());
  // console.log(a.getNowDate());
​
  function B (seconds) {
    A.call(this, seconds)
  }
  B.prototype = a
  let b = new B(1646120061037);
  console.log(b, b.getTime());
})()

image.png 缺点

1.每个属性在没有实例对象上面都是单独,不利于共享和节省内存空间

组合继承(构造函数+原型链)

(function () {
  function A (seconds) {
    this.TimeStr = new Date(seconds).toLocaleString()
  }
  //获取当前时间
  A.prototype.getNowDate = function () {
    console.log('getNowDate');
    return new Date().toLocaleString()
  }
  A.prototype.getTime = function () {
    return this.TimeStr
  }
  let a = new A();
  // console.log(a.getTime());
  // console.log(a.getNowDate());
​
  function B (seconds) {
    A.call(this, seconds)
  }
  B.prototype = a
  let b = new B(1646120061037);
  console.log(b, b.getTime());
})()

image.png

实例b存在两个TimeStr,一个在自身的属性,一个在原型链上,根据原型链查找规则:

image.png

当查找到b实例存在TimeStr时,不继续往后查找

缺点:

1.构造函数A被实例两次,原型链上存在重复属性TimeStr,造成内存空间的浪费

组合继承优化(构造函数+原型链)

(function () {
  function A (seconds) {
    this.TimeStr = new Date(seconds).toLocaleString()
  }
  //获取当前时间
  A.prototype.getNowDate = function () {
    console.log('getNowDate');
    return new Date().toLocaleString()
  }
  A.prototype.getTime = function () {
    return this.TimeStr
  }
  let a = new A();
  function B (seconds) {
    A.call(this, seconds)
  }
  B.prototype = Object.create(A.prototype)
  B.prototype.constructor = B
  B.prototype.getDays = function () {
    return new Date().getDay()
  }
  let b = new B(1646120061037);
  console.log(b, b.getTime(), b.getDays(), b instanceof (F));
})()

image.png \