javaScript 中的继承

2020-02-07  本文已影响0人  BitterOutsider

概要

  1. 继承的作用就是让代码拥有更好的复用性。
  2. 用原型链实现 javaScript 中的继承。
  3. 用 ES6 的 class 和 extends 改写代码。

原型链实现继承

实现 Asian 继承 Human。

私有属性 公有属性
Human name
birhday
species
act
useTool
Asian city bodyColor

Human 的构造函数:

function Human(option){
  this.name = option.name;
  this.birthday = option.birthday
}
Human.prototype.species = 'human'
Human.prototype.act = function(){/*行动*/}
Human.prototype.useTools = true

Asian 的构造函数:

function Asian(option){
  this.city = option.city
}
Asian.prototype.bodyColor = 'yellow'

继承:

在 Asian 的构造函数中 call Human 的构造函数,将 Asian 的 this 和 option传入。
将 Asian 的 proptotype 的原型指向 Human 的 protptype。

function Asian(option){
+ Human.call(this, option)
  this.city = option.city
}
+ Asian.prototype.__proto__ = Human.prototype

改进

  1. new Human
    在生产环境中不会去直接修改 __proto__,会带来一些隐患,而且浏览器也会给出警告。但又如何实现 Asian.prototype.__proto__ = Human.prototype
    在 new Human 时候,会运行以下代码:
{
  this = {}
  this.__proto = Human.prototype
  return this
}

由此可以这样写 Asian.prototype = new Human({name: '', birthday: ''})
其中 Asian.prototype === this(里面 return 的 this)
所以 Asian.prototype.__proto__ === this.__proto === Human.prototype
Asian.prototype.__proto__ === Human.prototype

  1. fakeHuman
    以上会在 Asian.prototype.proto 中生成空白字符 name 和 birthday,所以我们需要一个 fakeHuman。
function fakeHuman(){}
fakeHuman.prototype = Human.prototype
Asian.prototype = new fakeHuman
  1. 一个简单的方法(不兼容IE浏览器)
Asian.prototype = Object.create(Human.prototype)

ES6 中的继承

ES6 中引入了 class 和 extends 模拟 java 类的实现和继承。其本质还是 function。
缺点在于用 class 声明的函数不能 call 只能 new。这东西不像函数又不是类,就很奇怪。

class Human{
  constructor(option){
    this.name = option.name;
    this.birthday = option.birthday
  }
  act(){/*行动*/}
  species = 'human'
  useTools = true
}

class Asian extends Human{
  constructor(option){
    super(option)
    this.city = option.city
  }
  bodyColor = 'yellow'
}

var people = new Asian({city: '北京', name: 'Frank', birthday: '2000-10-10'})

完。

上一篇下一篇

猜你喜欢

热点阅读