最新的NodeJS(8)全面支持了類似Java的類和繼承機制,包括類的什么、繼承、靜態方法等。
類的什么
聲明一個類的方法通過class關鍵字,比如下面這樣:
class Person{
constructor(name,age){
this.name=name;
this.age=age;
}
getInfo(){
return this.name+':'+this.age;
}
}
從上面的代碼可以看出constructor相當於Java中的構造函數,對類的屬性name和age進行了初始化。
getInfo是類的方法,注意這里並沒有使用function關鍵字
如果我們要生成這個類的對象,通過new關鍵字就可以了:
var person=new Person("Eric",41);
console.log(person.getInfo());
類的繼承
類的繼承使用了extends關鍵字,像下面這樣:
class Student extends Person{
constructor(name,age,sex){
super(name,age);
this.sex=sex;
}
getInfo(){
return super.getInfo()+","+this.sex;
}
}
var student=new Student("Eric",41,"Male");
console.log(student.getInfo());
類的靜態方法
類中可以定義靜態方法,這樣就不用創建對象而是直接通過類名來調用類的方法,比如:
class Student extends Person{
constructor(name,age,sex){
super(name,age);
this.sex=sex;
}
getInfo(){
return super.getInfo()+","+this.sex;
}
static print(){
console.log("I'm static method!");
}
}
Student.print();
static 關鍵字將print方法定義為靜態方法,這樣我們就可以直接通過Student.print()來訪問它了。
————————————————
版權聲明:本文為CSDN博主「比特魚」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/yahoo169/article/details/79915977