類首先js并沒有真正的類系任,因為new關(guān)鍵詞會讓我們覺得js仿佛有真正的類恳蹲。但是僅僅是通過new 對函數(shù)進行了構(gòu)造調(diào)用虐块。產(chǎn)生的實例并不是完全沒有聯(lián)系的。他們通過[[prototype]]建立聯(lián)系嘉蕾。
繼承的本質(zhì):說的通俗的話就是讓一個類擁有使用另一個類成員變量,成員方法贺奠,靜態(tài)成員的權(quán)限,避免寫重復(fù)代碼
function Animal(age){
this.age = age;
}
Animal.prototype.say=function(){
console.log('我叫了兩聲')
}
//定義了一個類 成員屬性是 age 错忱,name ,成員方法是eat
function Dog(name){
Animal.call(this,19)
this.name = name
}
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
const dog =new Dog('dog')
dog.say();//'我叫了兩聲'
console.log(dog instanceof Animal)//true
console.log(Dog.prototype.constructor === Dog) //true
在上面例子中儡率。 實現(xiàn)了 Animal類 和 Dog 類, 其中Dog類繼承了Animal類的所有方法和成員變量.這就是所謂的繼承以清。
- es6實現(xiàn)類儿普, 和類的繼承
class Animal {
constructor(name) {
this.name = name
}
say() {
console.log('我的名字是' + this.name)
}
eat() {
console.log('吃飯')
}
}
class Person extends Animal {
constructor(job, age) {
super('人類')
this.job = job;
this.age = age
}
work() {
console.log(this.name + this.job)
}
get ages() {
return this.age +'歲'
}
set ages(val) {
return this.age = val
}
static war(){
console.log('發(fā)動戰(zhàn)爭')
}
}
const p1 = new Person('企業(yè)家', 21);
p1.say()
p1.work()
console.log(p1.ages)
p1.age = p1.age + 1;
console.log(p1.ages)
//我的名字是人類
//人類企業(yè)家
// 21歲
// 22歲
在這個例子中。 Person 類繼承了 Animal類的所有 屬性方法掷倔。
super關(guān)鍵字用于訪問父類的構(gòu)造函數(shù)眉孩。 必須在使用this前使用。不然勒葱,會報錯浪汪。static 給這個類聲明靜態(tài)成員。 get set 訪問器其實也就是加工 setter getter