JavaScript 实现继承的几种方式
一、原型继承
利用原型链,继承父级构造函数,继承原型上的方法
语法 : 子构造函数.prototype = new 父级构造函数 ( )
function Person(a) {} Person.prototype.eat=()=>{ console.log(吃); } function Son(b) {} Son.prototype = new Person() let son1 = new Son() son1.eat() //吃
扩展点 子构造函数原型上原来的constructor不指向原来的构造函数了
console.dir(Son); console.dir(Person);
解决方案 指回构造函数
Son.prototype.constructor = Son
二、组合继承
组合继承 : 属性 + 方法 (原型链 + call )
在原型的基础上 继承属性 :
是使用原型链实现对原型属性和方法的继承 (主要是方法),而通过借用构造函数来实现对实例属性构造的继承。
function Person(name, age) { this.name = name this.age = age } Person.prototype.eat = () => { console.log(吃); } function Son(name, age, hobby) { Person.call(this, name, age) //继承构造函数的属性 this.hobby = hobby } Son.prototype = new Person() let son1 = new Son(张三,18,写博客) son1.eat() Son.prototype.constructor = Son console.log(son1.name,son1.age,son1.hobby); // 张三,18,写博客
三、寄生组合继承
Son.prototype = new Person() console.dir(Son);
在组合继承的基础上发现 new Person时 Person并没有去使用,我们只是通过创建父构造函数时 去找构造函数的原型,并没有对父构造函数进行赋值等操作,所以就要对new Person进行优化。
只需要把new Person 改为 Object.creat(Person.prototype)
Son.prototype = Object.create(Person.prototype)
Object.create(对象) 做了两件事
Object.create 会创建一个新对象, 并且这个新对象的__proto__ 会指向传入的参数对象
四、class继承
重点 extends、super 先调用super在调用自己
// 继承关键字 => extends class Person { constructor (name, age) { this.name = name this.age = age } jump () { console.log(会跳) } } class Teacher extends Person { constructor (name, age, lesson) { super(name, age) // extends 中, 必须调用 super(), 会触发执行父类的构造函数 this.lesson = lesson console.log(构造函数执行了) } sayHello () { console.log(会打招呼) } } let teacher1 = new Teacher(zs, 18, 体育) console.log(teacher1)
上一篇:
Java基础知识总结(2021版)