原型鏈繼承
// 定義一個(gè)動(dòng)物類(lèi)
function Animal (name) {
? // 屬性
? this.name = name || 'Animal';
? // 實(shí)例方法
? this.sleep = function(){
? ? console.log(this.name + '正在睡覺(jué)!');
? }
}
// 原型方法
Animal.prototype.eat = function(food) {
? console.log(this.name + '正在吃:' + food);
};
子類(lèi):
function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
// Test Code
var cat = new Cat();
console.log(cat.name);//cat
console.log(cat.eat('fish'));//cat正在吃:fish? undefined
console.log(cat.sleep());//cat正在睡覺(jué)! undefined
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true
簡(jiǎn)單易于實(shí)現(xiàn),但是要想為子類(lèi)新增屬性和方法,必須要在new Animal()這樣的語(yǔ)句之后執(zhí)行,無(wú)法實(shí)現(xiàn)多繼承
構(gòu)造繼承--可以實(shí)現(xiàn)多繼承,不能繼承原型屬性/方法
function Cat(name){
? Animal.call(this);
? this.name = name || 'Tom';
}
實(shí)例繼承--不限制調(diào)用方式,但不能實(shí)現(xiàn)多繼承
function Cat(name){
? var instance = new Animal();
? instance.name = name || 'Tom';
? return instance;
}
拷貝繼承--支持多繼承,但是效率低占用內(nèi)存
function Cat(name){
? var animal = new Animal();
? for(var p in animal){
? ? Cat.prototype[p] = animal[p];
? }
? Cat.prototype.name = name || 'Tom';
}
組合繼承
function Cat(name){
? Animal.call(this);
? this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
寄生組合繼承
function Cat(name){
? Animal.call(this);
? this.name = name || 'Tom';
}
(function(){
? // 創(chuàng)建一個(gè)沒(méi)有實(shí)例方法的類(lèi)
? var Super = function(){};
? Super.prototype = Animal.prototype;
? //將實(shí)例作為子類(lèi)的原型
? Cat.prototype = new Super();
})();
ES6的extends繼承
//父類(lèi)
class Person {
? ? //constructor是構(gòu)造方法
? ? constructor(skin, language) {
? ? ? ? this.skin = skin;
? ? ? ? this.language = language;
? ? }
? ? say() {
? ? ? ? console.log('我是父類(lèi)')
? ? }
}
//子類(lèi)
class Chinese extends Person {
? ? constructor(skin, language, positon) {
? ? ? ? //console.log(this);//報(bào)錯(cuò)
? ? ? ? super(skin, language);
? ? ? ? //super();相當(dāng)于父類(lèi)的構(gòu)造函數(shù)
? ? ? ? //console.log(this);調(diào)用super后得到了this,不報(bào)錯(cuò),this指向子類(lèi),相當(dāng)于調(diào)用了父類(lèi).prototype.constructor.call(this)
? ? ? ? this.positon = positon;
? ? }
? ? aboutMe() {
? ? ? ? console.log(`${this.skin} ${this.language}? ${this.positon}`);
? ? }
}
//調(diào)用只能通過(guò)new的方法得到實(shí)例,再調(diào)用里面的方法
let obj = new Chinese('紅色', '中文', '香港');
obj.aboutMe();
obj.say();