ES6如何创建一个可继承class对象js如何创建一个class对象js如何实现继承类?构造函数,继承类,创建实例有什么样的关系?经常看class类的函数,之前看着总是头大,最近发现能写了、理解了、看懂了,卧槽!得记录一下。

ES6如何创建一个可继承的class类对象?-QUI-Notes

1.ES6创建对象类使用class

class Shape{ }

2.对象有参数,有自己得方法。参数用constructor构造声明,通过this获取对象得参数,并作为内部变量供方法使用。
另外,对象的方法可以自定义,但是不能用function声明了!

class Shape{
  // 创建构造函数
  constructor(name,area){
  this.name = name;
  this.area = area;
  }
  // 创建类的方法
  log(){ 
  console.log(this.name+"形," + "面积:" + this.area);
  }
 }

3.创建对象的实例,通俗点说就是,new声明定义一个对象

let cricle = new Shape('圆','200')

4.执行对象类的方法

cricle.log()

5.继承类和继承类的方法,继承类用关键词extends

class Cricle extends Shape{ }

6.继承父类:要用super直接调用父类的构造函数,包括父类的方法一起继承过来了!

class Cricle extends Shape{
  constructor(name,area,id){
  super(name,area); // super调用父类的构造函数
  this.id = id;
  }
}

7.重写方法,当子类的方法与父类不一样时就需要重写,子类的函数名与父类一致就会重写(子方法为空也会重写父类的方法)

class Cricle extends Shape{
  constructor(name,area,id){
  super(name,area); // super调用父类的构造函数
  this.id = id;
  }
  log(){ //重写替换父类的方法
  console.log("id为"+this.id +"的" + this.name+"形," + "面积:" + this.area);
  }
}

源码:

// 创建类
 class Shape{
  // 创建构造函数
  constructor(name,area){
  this.name = name;
  this.area = area;
  }
 
  // 创建类的方法
  log(){
  console.log(this.name+"形," + "面积:" + this.area);
  }
 }
  
  //继承类: extends关键字 
  class Cricle extends Shape{
  constructor(name,area,id){
  super(name,area); // super调用父类的构造函数
  this.id = id;
  }
 
  log(){ //替换父类的方法
  console.log("id为"+this.id +"的" + this.name+"形," + "面积:" + this.area);
  }
  }
  
  
  // 创建实例
  let cricle = new Shape('圆','200')
  cricle.log()
  
  let cricle1 = new Cricle('椭圆','300',10)
  cricle1.log()

这样就完成了js实现一个对象类并继承的方法,其实这样走下来发现并没有最初学习起来那么头大,并不难,看来真的需要不断的温故知新,这样才能把基础夯实!不废话了,end!