1. 程式人生 > >ES6 - 類的靜態方法和靜態屬性

ES6 - 類的靜態方法和靜態屬性

一、靜態方法

類的所有方法都定義在類的prototype屬性上面,所有類中定義的方法都會被例項繼承,如果在類方法前面加上static關鍵字就不會被例項繼承了。
靜態方法是直接通過類名來呼叫。

class Person{
	constructor(name="xf",age){
		this.name = name;
		this.age = age;
	}
	static say(){
		console.log("這是靜態方法");
	}
}
//通過類名來呼叫靜態方法
Person.say(); // 這是靜態方法

靜態方法也可以從super繼承呼叫 ,子類呼叫父類的static方法也只能在靜態函式中呼叫。

class Person{
	constructor(name="xf",age){
		this.name = name;
		this.age = age;
	}
	static say(){
		console.log("這是靜態方法");
	}
}
//通過類名來呼叫靜態方法
Person.say(); // 這是靜態方法

//子類繼承父類
class Child extends Person{
	//這裡沒寫建構函式,那麼就是預設有了空的建構函式並且預設呼叫了super()	
	static tell (){
	return this.say();
	//等同於 return super.say();
} } let child1 = new Child(); Child.tell(); // 這是靜態方法 Child.say(); // 這是靜態方法

二、靜態屬性

暫時沒有關鍵字來定義,想要實現的話就在定義完類之後直接在類上新增屬性,然後獲取的時候通過類名來獲取這個屬性。

class Person{
	constructor(name="xf",age){
		this.name = name;
		this.age = age;
	}
	static say(){
		console.log("這是靜態方法");
	}
}
// 模擬靜態屬性
Person.type = "這是模擬的靜態屬性"
; //訪問靜態屬性 console.log(Person.type); // 這是模擬的靜態屬性