定義一個(gè) class
每一個(gè)使用 class 方式定義的類(lèi)默認(rèn)都有一個(gè)構(gòu)造函數(shù) constructor() 函數(shù), 這個(gè)函數(shù)是構(gòu)造函數(shù)的主函數(shù), 該函數(shù)體內(nèi)部的 this 指向生成的實(shí)例。
class Person {
constructor(name) {
this.name = name;
}
say () {
console.log("hello " + this.name);
}
};
tom = new Person('tom')
tom.say()
// 運(yùn)行結(jié)果
hello tom
注意: ES6 中聲明的類(lèi)不存在函數(shù)聲明提前的問(wèn)題, 類(lèi)必須先聲明再使用,否則會(huì)出現(xiàn)異常。
靜態(tài)方法與靜態(tài)屬性
在類(lèi)的內(nèi)部,定義函數(shù)的時(shí)候, 在函數(shù)名前聲明了 static, 那么這個(gè)函數(shù)就為靜態(tài)函數(shù), 就為靜態(tài)方法, 不需要實(shí)例就可調(diào)用:
class Person {
constructor(name) {
this.name = name;
}
static say () {
console.log("hello world!");
}
};
Person.say()
// 運(yùn)行結(jié)果
hello world
只能在類(lèi)定義完畢以后再定義靜態(tài)屬性:
class Person {
constructor(name) {
this.name = name;
}
say () {
console.log("hello " + this.name);
}
};
Person.hands = 2;
console.log(Person.hands);
// 運(yùn)行結(jié)果
2
不能直接定義屬性我們可以使用 set 和 get:
class Person {
constructor(_name) {
this._name = _name;
}
get name() {
return this._name;
}
set name(_name) {
this._name = _name;
}
say () {
console.log("hello " + this.name);
}
};
// 測(cè)試
var tom = new Person('tom')
tom.name // tom
tom.name = 'tommy'
tom.name // tommy
類(lèi)的繼承 extends
本例中 X_Man 繼承了 Person 類(lèi),使用 extends 關(guān)鍵字表示:
class Person {
constructor(name) {
this.name = name;
}
say () {
console.log("hello " + this.name);
}
};
class X_Man extends Person {
constructor (name, power) {
super(name);
this.power = power;
}
show () {
console.log(this.name + ' has '+ this.power + ' power');
}
}
logan = new X_Man('logan', 100)
logan.show()
// 運(yùn)行結(jié)果
logan has 100 power
要使用繼承的話, 在子類(lèi)中必須執(zhí)行 super() 調(diào)用父類(lèi), 否者編譯器會(huì)拋錯(cuò)。
在子類(lèi)中的 super 有三種作用, 第一是作為構(gòu)造函數(shù)直接調(diào)用,第二種是作為父類(lèi)實(shí)例, 第三種是在子類(lèi)中的靜態(tài)方法中調(diào)用父類(lèi)的靜態(tài)方法。