Es6提供了新的構造函數寫法,引入了Class這個關鍵字來聲明一個構造函數
- old type
function Person(x,y){
this.x = x;
this.y = y;
}
Person.prototype.init = function(){}
//實例
new Person(1,2)
- now
class Person(){
constructor(x,y){
this.x = x;
this.y = y;
}
init(){}
}
//實例
new Person(1,2)
注意方法間不要加“,”
- 私有方法
私有方法,顧名思義,只在對象內部調用,是常用的需求
class List(){
_get(){
}
init(){}
}
//_get方法我用"_"做標示,證明他只在內部使用,是私有方法
- 繼承
子類必須在constructor方法中調用super方法,否則新建實例時會報錯。這是因為子類沒有自己的this對象,而是繼承父類的this對象,然后對其進行加工。如果不調用super方法,子類就得不到this對象。
class Person(){
constructor(x,y){
}
}
class students extends Person(){
constructor(x,y,z){
super(x,y);
this.z = z;
}
}
- set get
在Class內部可以使用get和set關鍵字,對某個屬性設置存值函數和取值函數。
看到這里,其實是可以實現一個很簡單的雙向綁定
class bind(){
constructor(ele){
this.ele = document.getElementBy(ele)
}
get html() {
return this.element.innerHTML;
}
set html(value)
{
this.element.innerHTML = value;
}
}
- 靜態方法
用static
修飾的方法,不能被實例繼承,直接在類上調用
class Person(){
static age(){ return 'hh'}
}
Person.age() ==> hh