1齿诉、什么是類
類是擁有相同屬性的對象,用于創(chuàng)建對象的模板培他。
2鹃两、如何實現(xiàn)類
1、ES6之前:
(1)舀凛、實現(xiàn)簡單的類:例1
function Dog(name){ //定義Dog是一種類,名字大寫
this.name = name //可以在對象內(nèi)定義自有屬性
this.legsNumber = 4
}
Dog.prototype.kind = '狗' //可以定義公有屬性是kind
Dog.prototype.say = function(){ //可以定義公有屬性say方法
console.log(`我是${this.name}途蒋,我有${this.legsNumber}條腿猛遍。`)
}
const d1 = new Dog('旺財') // Dog 函數(shù)就是一個類
d1.say() //打印出:我是旺財,我有4條腿号坡。
(2)懊烤、實現(xiàn)類的繼承:例2
function Animal(legsNumber){ //父類Animal
this.legsNumber = legsNumber //父類的自有屬性
}
Animal.prototype.kind = '動物' //父類的公有屬性
function Dog(name){ //子類繼承父類方法和自有屬性
this.name = name
Animal.call(this, 4) // 關(guān)鍵代碼1
}
Dog.prototype.__proto__ = Animal.prototype // 關(guān)鍵代碼2,但這句代碼被禁用了宽堆,怎么辦
Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`我是${this.name}腌紧,我有${this.legsNumber}條腿。`)
}
const d1 = new Dog('旺財') // Dog 函數(shù)就是一個類
console.dir(d1)
上述子類實現(xiàn)父類繼承是關(guān)鍵代碼1和關(guān)鍵代碼2兩處
Dog.prototype.__proto__ = Animal.prototype // 一般不推薦這樣寫
如果這句代碼不被推薦或者被禁用了畜隶,可以寫成下面的:
var f = function(){ }
f.prototype = Animal.prototype
Dog.prototype = new f()
2壁肋、ES6:更加規(guī)范化去定義一個類。
語法:
class xxx { //首先先寫class代表這是一個類對象,xxx是表示一個類的名字(大寫)
constructor(a) { //constructor構(gòu)造函數(shù)籽慢,可以進(jìn)行傳參浸遗,里面主要是定義類的自有屬性
...
}
yyy(){ //yyy表示xxx類的公有屬性的方法
...
}
}
const d1 = new xxx('') //
(1)、將上述例1改成ES6用class生成的類:
class Dog {
kind = '狗' // 等價于在 constructor 里寫 this.kind = '狗'
constructor(name) {
this.name = name
this.legsNumber = 4
}
say(){
console.log(`汪汪汪~ 我是${this.name}箱亿,我有${this.legsNumber}條腿跛锌。`)
}
}
const d1 = new Dog('旺財')
d1.say()
(2)、將上述例2改成ES6用class生成的類:
class Animal{
constructor(legsNumber){
this.legsNumber = legsNumber
}
}
class Dog extends Animal{ //在子類中使用extends關(guān)鍵字届惋,代表Dog繼承Animal
constructor(name) {
super(4) //使用關(guān)鍵字super()代表使用父類方法和屬性
this.name = name
}
say(){
console.log(`汪汪汪~ 我是${this.name}髓帽,我有${this.legsNumber}條腿。`)
}
}
const d1 = new Dog('旺財') // Dog 函數(shù)就是一個類
console.dir(d1)