ES6支持通过class关键字定义类,可以看成一个语法糖,它的绝大部分功能ES5都可以做到,新的class写法让对象原型的写法更加清晰。
class类
在ES6之前的构造函数写法如下:
function Fun (a,b){
this.x = a
this.y = b
}
Fun.prototype.getX = ()=>{console.log(x)} //函数原型添加方法
Fun.name = 'Tom' // 这个是函数属性,实例对象无法访问!
使用ES6的class写法就可以写成下面的形式:
class Fun{
// 等价于构造函数体
constructor(a,b){
this.x = a
this.y = b
}
// 等价于在Fun函数的原型上定义 Fun.prototype.getX
getx(){
console.log(x)
}
// 等价Fun的私有方法,实例对象无法访问
static name = 'Tom'
}
class类的getter跟setter
除了上面的配置外,class类里面还可以使用get跟set来修饰方法,语法为 get/set 属性名() {},分别表示读取属性/设置属性时调用此函数,其中 set函数接收一个参数,表示所设置的值:
class Text{
get word(){
return 'book'
}
set word(val){
console.log(val)
}
}
// 实例化
let t = new Text()
console.log(t.word) // book
t.word = 'look' // look
类的继承
在ES5中,我们可以调用一个函数的call()方法来改变里面的this指向,那么在一个子类想要继承父类的属性或方法时就可以在子类中调用父类的call方法,改变父类的this指向来达到继承的效果:
// 定义父类
function far(a){
this.sex = a
}
// 定义子类
function son(sex,age){
far.call(this,sex) // 将far代码里面的this改成son里面的this,代码里没有使用this的则不会继承到子类来。
this.age = age
}
son.prototype = new far() // 继承父类原型上的方法,上面调用call是继承父类本身的属性
son.prototype.constructor = son
在ES6使用class类的继承,在子类调用super()
// 父类
class Far{
constructor(a,b){
this.a = a
this.b = b
}
say(){
console.log('hello')
}
}
// 子类
class Son extends Far{
constructor(a,b,c,d){
super(a,b) // super只能在constructor里使用,继承父类的属性与方法
this.c = c
this.d = d
}
bye(){
console.log('bye')
}
}