ES6 class类 及继承

目录

1.如何理解class

2.class基本语法

 3.class的继承


1.如何理解class

        在javascript语言中,生成实例对象使用构造函数;ES6提供了类Class这个概念,作为对象的模板。定义一个类通过class关键字,ES6的类可以看成是构造函数的另一种写法。

2.class基本语法

class Person{

//本质上实例属性和方法是声明在Person.prototype中的

//constructor构造器,当我们用class类new一个对象时,会默认调用构造器

//里面声明实例属性

    constructor(name,age){

        this.name=name;

        this.age=age

  }

//实例方法

    sayName(){

        console.log(this.name)

    }

//而静态属性和方法要用关键字 static 来修饰,本质上他们都是放在构造函数Class上的,只能通过class构造函数来调用

//静态属性

static weight = '50KG'

//静态方法

static sayWeight(){

    console.log(this.weight);

          }

}

//class实例化

let tom =new Person('tom', 20, 'male')

 3.class的继承

        class 可以通过extends关键字实现继承,子类可以没有构造函数,系统会默认分配。子类提供了构造函数则必须要显式调用super。super函数类似于借用构造函数。类似于Animal.call()

//父类class构造函数

class Animal {

  static animalAttr = 'Animal静态属性';

  constructor(name,age){

    this.name = name;

    this.age = age

  }

  animalFun(){

    console.log('Animal实例方法');

  }

  static animalStaFun(){

    console.log('animalStaFun静态方法');

  }

}

//子类构造函数        用extends关键字来表明继承的父类对象

class Dog extends Animal{

  constructor(name,age,color,weight){

    // 显示调用super并传递继承的属性就会去寻找extends继承的父构造函数中的数据

    super(name,age)

    this.color = color;

    this.weight = weight;

  }

}

子构造函数实例化,并验证是否继承了父类的实例属性和方法

 let dog = new Dog('二狗',4, 'black', '10kg')

//调用父构造函数的属性和方法

console.log(dog);        //Dog { name: '二狗', age: 4, color: 'black', weight: '10kg' }

dog.animalFun();        //Animal实例方法

 验证Dog是否继承了父类的静态属性和方法

console.log(Dog.animalAttr);  //Animal静态属性

Dog.animalStaFun()            //animalStaFun静态方法

验证总结

//子类原型对象继承父类原型对象

console.log(Dog.prototype.__proto__ === Animal.prototype);   //true

//子类对象指向父类对象

console.log(Dog.__proto__ === Animal);      //true


版权声明:本文为qq_45867474原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。