Class 類
基礎(chǔ)知識
為了和其他語言繼承形態(tài)一致,JS提供了class 關(guān)鍵詞用于模擬傳統(tǒng)的class ,但底層實現(xiàn)機(jī)制依然是原型繼承。
class 只是為了讓類的聲明與繼承更加簡潔清晰。
聲明定義
可以使用類聲明和賦值表達(dá)式定義類,推薦使用類聲明來定義類
//類聲明
class User {
}
console.log(new Article());
let Article = class {
};
console.log(new User());
構(gòu)造函數(shù)
使用 constructor 構(gòu)造函數(shù)傳遞參數(shù),下例中show為構(gòu)造函數(shù)方法,getName為原型方法
-
constructor會在 new 時自動執(zhí)行
class User {
constructor(name) {
this.name = name;
this.show = function() {};
}
getName() {
return this.name;
}
}
const xj = new User("ss");
console.log(ss);
構(gòu)造函數(shù)用于傳遞對象的初始參數(shù),但不是必須定義的
等價于ES5中
Function User(name){
this.name = name;
this.show = function() {};
}
}
User.prototype.getName=function () {
return this.name;
}
const xj = new User("ss");
console.log(xj);