其他分享
首页 > 其他分享> > js继承.

js继承.

作者:互联网

JS 继承实现⽅式也很多,主要分 ES5 和 ES6 继承的实现 先说⼀下 ES5 是如何实现继承的 ES5 实现继承主要是基于 prototype 来实现的,具体有三种⽅法 ⼀是 原型链继承:
  1. 父类的实例作为子类的原型
function Woman(){ 
    }
Woman.prototype= new People();
Woman.prototype.name = 'haixia';
let womanObj = new Woman();

  即   B . prototype = new A ()

优点:

缺点:

⼆是借⽤构造函数继承 ( call 或者 apply 的⽅式继承 )
function B(name,age) {
        A.call(ths,name,age)
}
​​​​​​​
function Woman(name){
 //继承了People
  People.call(this); //People.call(this,'tom); 
  this.name = name || 'kitty'
}
let womanObj = new Woman();

优点:

缺点:

三是组合继承
  1. 调用父类构造函数,继承父类的属性,通过将父类实例作为子类原型,实现函数复用
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)
}
Woman.prototype = new People();
Woman.prototype.constructor = Woman;
let wonmanObj = new Woman(ren,27);
wonmanObj.eat(); 

缺点:

优点:

组合继承是结合第⼀种和第⼆种⽅式 再说⼀下 ES6 是如何实现继承的

代码量少,易懂

ES6 继承是⽬前⽐较新,并且主流的继承⽅式,⽤ class 定义类,⽤ extends 继承类,⽤ super () 表示⽗类 , 【下⾯代码部分只是熟悉,不⽤说课】 例如:创建 A 类
class A {
        constructor() {
        //构造器代码,new时⾃动执⾏
        }
⽅法1( ) { //A类的⽅法 }
⽅法2( ) { //A类的⽅法 }
    }
创建B类并继承A类
class B extends A {
 constructor() {
 super() //表示⽗类
 }
}
实例化B类: var b1=new B( )
 b1.⽅法1( )
//class 相当于es5中构造函数
//class中定义方法时,前后不能加function,全部定义在class的protopyte属性中
//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中实现的原理。
 

标签:Woman,name,继承,age,js,父类,class
来源: https://blog.csdn.net/A535366/article/details/120443163