es6语法Class关键字和继承

2019-08-24  本文已影响0人  2019Say10

1.class

class的含义就是表示一类事物,把拥有相同一些属性的事物定义为一个类,其中使用构造来获取保存传入的参数,但在es5中似乎由构造函数就包含了类和构造.这样定义语义并不明确,而class关键字的引入就更加规范,更容易理解。
es6中定义一个class类

class roundness{
    constructor(length){
        this.length=length
    }
    area(){
        return length*length
    }
}

class Rectangle{
  //构造方法
    constructor(recWith,recHeight){
        this.recWith=recWith
        this.recHeight=recHeight
    }
  //方法
    area(){
        return this.recWith*recHeight
    }
    perimeter(){
        retrun (recWith+recHeight)*2
    }
}

定义了一个User类,在构造方法中传入参数.其中的this指向为当前类.在使用类时.必须通过new关键字实例化一个对象.在类内部没有构造方法时,会默认的调用一个无参数的构造方法.

2.继承

面向对象的一个特征就是继承,在没使用exends关键字时,js的继承使用的是改变子类的原型对象完成继承代码如下:

function User(name,age){
    this.name=name
    this.age=age
}
User.prototype.show=function(){
    console.log("这是一个用户")
}
function VipUser(type){
    this.type=type
}
VipUser.prototype=new User("joker",'age')
VipUser.prototype.constructor=VipUser
let vipUser=new VipUser("ViP")

而使用extends就简单多了

class User {
    constructor(name,age){
        this.name=name
        this.age=age
    }
    show(){
        console.log("这是一个普通用户")
    }
}
class VipUser extends User{
    constructor(name,age,type){
        super(name,age)//调用父类的构造
        this.type=type
    }
    show(){
        "这是一个vip用户"
    }
}
let vipUser=new VipUser("joke","20","vip")

//其中super必须写,表示从父类的构造中获取数据
如果子类没有构造方法则会调用一个默认的构造方法

class VipUser extends User {
}

// 等同于
class VipUser extends User {
  constructor(...args) {
    super(...args);
  }
}

其中super表示父级对象,可以通过super重写父级方法

class VipUser extends User{
    constructor(name,age,type){
        super(name,age)//调用父类的构造
        super.show=function(){
            console.log("这是一个vip用户")
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读