1.class
class的含義就是表示一類事物,把擁有相同一些屬性的事物定義為一個類,其中使用構(gòu)造來獲取保存?zhèn)魅氲膮?shù),但在es5中似乎由構(gòu)造函數(shù)就包含了類和構(gòu)造.這樣定義語義并不明確,而class關(guān)鍵字的引入就更加規(guī)范,更容易理解。
es6中定義一個class類
class roundness{
constructor(length){
this.length=length
}
area(){
return length*length
}
}
class Rectangle{
//構(gòu)造方法
constructor(recWith,recHeight){
this.recWith=recWith
this.recHeight=recHeight
}
//方法
area(){
return this.recWith*recHeight
}
perimeter(){
retrun (recWith+recHeight)*2
}
}
定義了一個User類,在構(gòu)造方法中傳入?yún)?shù).其中的this指向為當前類.在使用類時.必須通過new關(guān)鍵字實例化一個對象.在類內(nèi)部沒有構(gòu)造方法時,會默認的調(diào)用一個無參數(shù)的構(gòu)造方法.
2.繼承
面向?qū)ο蟮囊粋€特征就是繼承,在沒使用exends關(guān)鍵字時,js的繼承使用的是改變子類的原型對象完成繼承代碼如下:
function User(name,age){
this.name=name
this.age=age
}
User.prototype.show=function(){
console.log("這是一個用戶")
}
function VipUser(type){
this.type=type
}
VipUser.prototype=new User("joker",'age')
VipUser.prototype.constructor=VipUser
let vipUser=new VipUser("ViP")
而使用extends就簡單多了
class User {
constructor(name,age){
this.name=name
this.age=age
}
show(){
console.log("這是一個普通用戶")
}
}
class VipUser extends User{
constructor(name,age,type){
super(name,age)//調(diào)用父類的構(gòu)造
this.type=type
}
show(){
"這是一個vip用戶"
}
}
let vipUser=new VipUser("joke","20","vip")
//其中super必須寫,表示從父類的構(gòu)造中獲取數(shù)據(jù)
如果子類沒有構(gòu)造方法則會調(diào)用一個默認的構(gòu)造方法
class VipUser extends User {
}
// 等同于
class VipUser extends User {
constructor(...args) {
super(...args);
}
}
其中super表示父級對象,可以通過super重寫父級方法
class VipUser extends User{
constructor(name,age,type){
super(name,age)//調(diào)用父類的構(gòu)造
super.show=function(){
console.log("這是一個vip用戶")
}
}
}