js继承?

tech2022-07-09  170

1、js继承

继承概念:通过某种方式让一个对象可以访问到另一个对象的属性和方法,把这种方式称之为继承。继承是为了获取更多的拓展,减少代码的冗余

1、原型链继承

基本思路:原型链继承的基本思想是利用原型让一个引用类型可以访问,另一个引用类型的属性和方法。

function sup(){ this.name=["王二","李四"]; } function suber(){} suber.prototype=new sup(); //继承sup let a=new suber() console.log(a.name) //[ '王二', '李四' ]

优点: 1、简单易于实现,父类的新增的实例与属性子类都能访问

缺点: 1、不可以实现多继承 2、在创建子类型的实例时,没有办法在不影响所有对象实例的情 况下给父类型的构造函数中传递参数。

2、借用构造函数继承

基数本思路:在子类型的构造函数中调用父类构造函数。

function sup(){ this.name=["王二","李四"]; } function suber(){ sup.call(this) } let a=new suber() console.log(a.name) //[ '王二', '李四' ]

优点: 1、可以向超类传递参数 2、可以实现多继承(call或者apply多个父类)

缺点: 1、方法都在构造函数中定义,函数复用无从谈起,在父类型原型中定义的方法对于子类型而言都是不可见的。

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

基本思路: 1、在子类构造函数中 调用父类构造函数,并通过 call 改变 this 的指向 ,继承了父类的属性 2、通过 new 一个父类的实例作为子类构造函数的原型prototype ,原型链方式来继承父类的方法

function sup(age){ this.name=["王二","李四"]; this.age=age } function suber(age){ sup.call(this,age) } suber.prototype=new sup(); let a=new suber([15,38]) console.log(a.name) //[ '王二', '李四' ] console.log(a.age) //[ 15, 38 ]

优点: 1.可以向超类传递参数 2.每个实例都有自己的属性 3.实现了函数复用

缺点: 无论什么情况下,都会调用两次超类型构造函数:一次是在创建子类型原型的时候,另一次是在子类型构造函数内部。

4、原型式继承

基本思路:借助原型可以基于已有的对象创建新对象,同时还不必因此创建自定义 类型。

let name = { name: ["王二", "李四"] }; function sup(name) { function suber() {} suber.prototype = name; return new suber(); } let a = sup(name); console.log(a); //suber { // __proto__: // name: (2) ["王二", "李四"] // __proto__: Object }

优点: 1、不限制调用方式 2、简单,易实现

缺点: 1、不能多次继承

5.寄生组合继承

通过寄生的方式来修复组合式继承的不足,完美的实现继承.

//父类 function People(name,age){ this.name = name || 'wangxiao' this.age = age || 27 } //父类方法 People.prototype.eat = function(){ return this.name + this.age + 'eat sleep' } //子类 function Woman(name,age){ //继承父类属性 People.call(this,name,age) } //继承父类方法 (function(){ // 创建空类 let Super = function(){}; Super.prototype = People.prototype; //父类的实例作为子类的原型 Woman.prototype = new Super(); })(); //修复构造函数指向问题 Woman.prototype.constructor = Woman; let womanObj = new Woman();
6.es6继承
//class 相当于es5中构造函数 //class中定义方法时,前后不能加function,全部定义在class的prototype属性中 //class中定义的所有方法是不可枚举的 //class中只能定义方法,不能定义对象,变量等 //class和方法内默认都是严格模式 //es5中constructor为隐式属性 class People{ constructor(name='wang',age='27'){ this.name = name; this.age = age; } eat(){ console.log(`${this.name} ${this.age} eat food`) } } //继承父类 class Woman extends People{ constructor(name = 'ren',age = '27'){ //继承父类属性 super(name, age); } eat(){ //继承父类方法 super.eat() } } let wonmanObj=new Woman('xiaoxiami'); wonmanObj.eat();

ES5继承和ES6继承的区别: es5继承首先是在子类中创建自己的this指向,最后将方法添加到this中 Child.prototype=new Parent() || Parent.apply(this) || Parent.call(this) es6继承是使用关键字先创建父类的实例对象this,最后在子类class中修改this

结束语: es6中很多代码的语法糖,很多方法简单易用。在浏览器兼容的情况下,改变原有方式。 虽然现在很多框架都是es6,但对于初学者还是建议多看看es5中实现的原理。

最新回复(0)