一、ES6如何创建类
class name{
// 定义一个构造函数
constructor(uname){
// this指向的是实例对象
// uname是实例对象传进来的参数,
// 实例对象new了类,自动会执行constructor构造函数
this.uname = uname
}
}
// 通过new关键字来实例化一个对象
let ldh = new name('刘德华')
console.log(ldh.name) //刘德华
二、子类继承父类
class Father{
// 构造函数接收参数
constructor(x,y){
this.x = x;
this.y = y;
}
// 在父类当中定义方法
sum(){
// 输出相加
console.log(this.x + this.y)
}
}
// 定义一个子类,继承父类的方法
class Son extends Father{
// 接收实例对象传过来的参数
constructor(x,y){
super(x,y)
}
}
// 实例化子类
let sum = new Son(1,2)
sum.sum() //3
- 在继承当中,子类通过使用super函数来对父元素传递参数
- 先通过子类实例化一个对象,传递参数进去,先经过子类的constructor构造函数