ES5,ES6 继承

ES5:

对象冒充继承:不能继承原型链上的属性和方法,实例化子类可以给父类传值

原型链继承:可以继承构造函数以及原型链上的属性和方法,实例化子类的时候没法给父类传参

所以一般是两个一起用

 function Person(name,age){
   this.name = name;
   this.age = age;
   this.run = function(){
     console.log(`${this.name}----${this.age}`)
   }
 }
 Person.prototype.work = function(){
   console.log("work")
 }
 function Web(name,age){
   Person.call(this,name,age) /**** 对象冒充实现继承 ****/
 }
 Web.prototype = new Person()   /**** 原型链继承 ****/
 var w = new Web('李四','20');
 w.run();        // 输出:李四----20 undefined----undefined 
 w.work();     // 输出:w.work is not a function work 
 有蓝色时:输出蓝色 ,即继承属性方法
 有红色时:输出红色,即继承原型

ES6:

 

 

class Person{
  constructor(name,age){ /** 类的构造函数,实例化的时候执行,new的时候执行 **/
   this.name = name; 
    this.age = age;
   } 
   getName(){
    console.log(this.name);
   }

   setName(name){
     this.name = name
   }

   getInfo(){
     console.log(`姓名:${this.name}---年龄:${this.age}`)
   }

   静态方法
   static work(){
     console.log("这是es6里的静态方法")
   }
 }

  继承:

  class Web extends Person{      定义了Web类,继承了Person所有方法和属
   constructor(name,age,sex){     //父类
     super(name,age);  // 实例化子类的时候给父类传参 ( 表示父类的构造函数,用来新建父类的this对象。 子类实例的构建,基于父类实例,只有super方法才能调用父类实例。) 
     this.sex = sex;
   }
   print(){
     console.log(this.sex)
   }
  }

  var w = new Web('李四','20','男')
  w.print()      // 输出:男
  w.getInfo()  // 输出:姓名:李四---年龄:20
  Person.work();  // 这是es6里的静态方法
  console.log(Person.instance);   //  这是一个静态方法

 

 

原文地址:https://www.cnblogs.com/init00/p/12581777.html