JavaScript 面向对象-原型继承

原型链继承

1function Person(name) {
2  this.name = name
3}
4Person.prototype.fn = function () {
5  console.log('parent')
6}
7function Child() {}
8Child.prototype = new Person('name') // new 之后 只是实例化的对象,下面有 __proto__
9Child.prototype.constructor = Child // 手动修改回来
10const child = new Child()
11// 在原型上继承,子类不能修改和传参进去

对象冒充继承(借用构造函数

1function Parent(name) {
2  this.name = name
3}
4Parent.prototype.fn = function () {
5  console.log('parent')
6}
7function Child(name) {
8  Parent.call(this, name)
9}
10const child = new Child('xiaohong')

组合继承

1function Parent(name) {
2  this.name = name
3}
4Parent.prototype.eat = function () {
5  console.log('11')
6}
7function Child(name) {
8  Person.call(this, name)
9}
10Child.prototype.eat = Parent.prototype
11Child.prototype.constructor = Child

寄生式组合继承

1function Parent(name) {
2  this.name = name
3}
4Parent.prototype.aa = function () {
5  console.log('aa')
6}
7
8function inherit(Child, Parent) {
9  function Super() {}
10  Super.prototype = Parent.prototype
11  Child.prototype = new Super()
12  Child.prototype.constructor = Child
13}
14
15function Child() {}
16inherit(Child, Parent)
17const child = new Child()

for...in 继承

1// 遍历父原型对象
2for (funName in Person.prototype) {
3  // 子构造函数原型属性 = 父原型对象的属性
4  NewPerson.prototype[funName] = Person.prototype[funName]
5}

Object.create()继承

create 创建新对象

1NewPerson.prototype = Object.create(Person.prototype)