类的声明
class Person{
constructor(name){
this.name = name
}
sayName(){
console.log(this.name)
}
}
通过类的声明语法定义构造函数的行为和之前创建的构造函数的过程类似,只是这里直接在class中通过特殊的constructor方法来定义构造函数。
自身属性是实例中的属性,不会出现在原型链中,且只能在类的构造器或则方法中创建。
为何使用class语法
- 函数声明可以被提升,而class声明与let声明类似,不能被提升
- 类声明中所有的代码将自动运行在严格模式下,且无法强行让代码脱离严格模式
- 类中所有的方法都是不可枚举的
-
继承
ES6之前的继承
function Rec( length,width){
this.length = length
this.width = width
}
Rec.prototype.getArea = function(){
return this.length*this.width
}
function Square(l,w){
Rec.call(this,l,w)
}
Square.prototype = Object.create(Rec.prototype,{
constructor:Square
})
ES6之后的继承
类的出现让我们可以更轻松的实现继承的功能,使用熟悉的extends关键字可以指定类继承的函数。原型可以自动调整,通过调用super()方法即可访问基类的构造函数
class Rec{
constructor(l,w){
this.l=l;
this.w=w
}
getArea(){
return this.l*this.w
}
}
class Squ extends Rec{
constructor(l){
super(l,l)//相当于Rec.call(this,l,l)
}
}
let sq = new Squ(2);
console.log(sq.getArea())