class类
在ES6 中引入了class类这个概念,那么这个class究竟是什么怎么用呢?可能对于初学者的我们来说,有时候说多了反而不理解,我举了个例子,如下:
经常听到老师们会说构造函数的首字母要大写,普通函数不用大写,这个只是大家方便区别构造函数和函数。然后到了ES6我们的构造函数就可以写成class了,也是引入了其他语言的类概念。
下面这个例子就是一个简单的构造函数,但是函数和构造函数单从表现来看过于相似,于是ES6的class类应呼而出,帮我们更加容易的区分。我们也看看ES6是怎么写如下代码的吧
function Person(){ //ES5 方法
this.name='zzl',
this.age=18
}
Person.prototype.say=function(){
console.log(this.name+'say hello')
}
var p1=new Person();
p1.say(); //zzlsay hello
class Person{ //ES6 方法
constructor(){
this.name='zzl'
this.age=18
}
say(){
console.log(this.name+'say hello')
}
}
var p1=new Person();
p1.say(); //zzlsay hello
上面我用ES6的方法重新写了一遍,中间有啥区别呢?
constructor():这是一个特殊的类方法,描述大体意思就是,它既不是静态方法也不是实例方法,它仅在实例化的时候被调用。
注意点:一个class里面只能有一个constructor()方法,不然就会报错。
如果没有定义constructor()方法,系统也会默认给它添加,简单的说就是每个class必有一个construtor。
原型方法:在ES5中,我们往往把原型方法定义在它的prtototype上,而ES6中,原型方法直接写在class里面,它的方法名前面不需要加上function,如上面例子所示,另外方法和方法之间不需要用逗号隔开,否则会报错。
听到这里有没有觉的ES6的class还是很简洁的哟。
使用ES6的class需要注意的地方:由于ES6 的class 预解析的时候没有提升功能,而ES5 可以当成函数来提升,所以ES6的class 实例话对象的操作一定要放在class类的后面写,例如:
//正确的写法
class Person{
constructor(){
this.name='zzl'
this.age=18
}
say(){
console.log(this.name+'say hello')
}
}
var p1=new Person();
p1.say(); //zzlsay hello
//错误的写法
var p1=new Person();
p1.say(); //Uncaught ReferenceError: Person is not defined
class Person{
constructor(){
this.name='zzl'
this.age=18
}
say(){
console.log(this.name+'say hello')
}
}
extends 继承:用于实现class类之间的继承 。子类继承父类,相当于继承了家产一样,继承了父类所有的属性和方法。并且每次 extends后面只能跟一个父类 , 举个栗子:
class Father{
constructor(){
this.name='father'
this.money=60000
}
say(){
console.log(`${this.name} say hello`)
}
mymoney(){
console.log(`${this.name} has ${this.money}$ `)
}
}
class Son extends Father{
constructor(){
super() // 注意这个一定要写
this.name='son'
this.money=60000
}
}
var son1=new Son();
son1.say(); //son say hello
son1.mymoney(); //son has 60000$
上面的例子可以看出子类完全继承了父类的方法,最智能的是当子类使用父类里面的方法时,this会自动指向子类构造器。
注意点:子类里面的super()是用来调用其父类的constuctor或者父类里的方法的。不写的话会报错。
class 的静态方法:在class类中某个方法前加上关键字static,表示该方法不会被实例继承,只能通过class类本身来调用,这就是静态方法。下面举个简单的例子:
下面例子中father为class类,f1就是它实例, 我在say方法前添加static关键字, 运行f1.say()报错说找不到方法,运行Father.say()则调用了say方法。说明,静态方法不能继承到实例上。可以在类本身上调用。
class Father{
constructor(){
this.name='father'
this.money=60000
}
static say(){
console.log(`${this.name} say hello`)
}
mymoney(){
console.log(`${this.name} has ${this.money}$ `)
}
}
var f1=new Father();
// f1.say(); //f1.say is not a function
Father.say(); //Father say hello
另外,父类的静态方法,可以被子类所继承。例如:
Son 类继承了 Father类的静态方法, Son直接在类本上调用继承来的方法。
class Father{
constructor(){
this.name='father'
this.money=60000
}
static say(){
console.log(`${this.name} say hello`)
}
mymoney(){
console.log(`${this.name} has ${this.money}$ `)
}
}
class Son extends Father{
constructor(){
super() // 注意这个一定要写
this.name='son'
this.money=60000
}
}
Son.say(); //Son say hello
如果有什么错误欢迎留言指出,谢谢。