類 & 繼承
類也是 ES6 一個不可忽視的新特性,雖然只是句法上的語法糖,但是相對于 ES5撮躁,學(xué)習(xí) ES6 的類之后對原型鏈會有更加清晰的認(rèn)識。
特性
1买雾、本質(zhì)為對原型鏈的二次包裝
2把曼、類沒有提升
3、不能使用字面量定義屬性
4漓穿、動態(tài)繼承類的構(gòu)造方法中 super 優(yōu)先 this
類的定義
/* 類不會被提升 */
let puppy = new Animal('puppy'); // => ReferenceError
class Animal {
constructor(name) {
this.name = name;
}
sleep() {
console.log(`The ${this.name} is sleeping...`);
}
static type() {
console.log('This is an Animal class.');
}
}
let puppy = new Animal('puppy');
puppy.sleep(); // => The puppy is sleeping...
/* 實例化后無法訪問靜態(tài)方法 */
puppy.type(); // => TypeError
Animal.type(); // => This is an Animal class.
/* 實例化前無法訪問動態(tài)方法 */
Animal.sleep(); // => TypeError
/* 類不能重復(fù)定義 */
class Animal() {} // => SyntaxError
以上我們使用 class 關(guān)鍵字聲明了一個名為 Animal 的類嗤军。
雖然類的定義中并未要求類名的大小寫,但鑒于代碼規(guī)范晃危,推薦類名的首字母大寫叙赚。
兩點注意事項:
在類的定義中有一個特殊方法 constructor(),該方法名固定山害,表示該類的構(gòu)造函數(shù)(方法)纠俭,在類的實例化過程中會被調(diào)用(new Animal('puppy'));
類中無法像對象一樣使用 prop: value 或者 prop = value 的形式定義一個類的屬性浪慌,我們只能在類的構(gòu)造方法或其他方法中使用 this.prop = value 的形式為類添加屬性冤荆。
最后對比一下我們之前是怎樣寫類的:
function Animal(name) {
this.name = name;
}
Animal.prototype = {
sleep: function(){
console.log('The ' + this.name + 'is sleeping...');
}
};
Animal.type = function() {
console.log('This is an Animal class.');
}
//class 關(guān)鍵字真真讓這一切變得清晰易懂了~類的繼承
class Programmer extends Animal {
constructor(name) {
/* 在 super 方法之前 this 不可用 */
console.log(this); // => ReferenceError
super(name);
console.log(this); // Right!
}
program() {
console.log("I'm coding...");
}
sleep() {
console.log('Save all files.');
console.log('Get into bed.');
super.sleep();
}
}
let coder = new Programmer('coder');
coder.program(); // => I'm coding...
coder.sleep(); // => Save all files. => Get into bed. => The coder is sleeping.
這里我們使用 class 定義了一個類 Programmer,使用 extends 關(guān)鍵字讓該類繼承于另一個類 Animal权纤。
如果子類有構(gòu)造方法钓简,那么在子類構(gòu)造方法中使用 this 對象之前必須使用 super() 方法運行父類的構(gòu)造方法以對父類進(jìn)行初始化。
在子類方法中我們也可以使用 super 對象來調(diào)用父類上的方法汹想。如示例代碼中子類的 sleep() 方法:在這里我們重寫了父類中的 sleep() 方法外邓,添加了兩條語句,并在方法末尾使用 super 對象調(diào)用了父類上的 sleep() 方法古掏。
俗話講:沒有對比就沒有傷害 (*゜ー゜*)损话,我們最后來看一下以前我們是怎么來寫繼承的:
function Programmer(name) {
Animal.call(this, name);
}
Programmer.prototype = Object.create(Animal.prototype, {
program: {
value: function() {
console.log("I'm coding...");
}
},
sleep: {
value: function() {
console.log('Save all files.');
console.log('Get into bed.');
Animal.prototype.sleep.apply(this, arguments);
}
}
});
Programmer.prototype.constructor = Programmer;
如果前文類的定義中的前后對比不足為奇,那么這個。丧枪。光涂。