面向對象三大特徵:
一、 封裝:隱藏內部的細節,不暴露在外面(不讓其它訪問僅能自己訪問)
//在js中利用函數的作用域來模擬
// 封裝
let Pet=function (name,types) {
this.name=name;
//封裝,將變量用一個關鍵字聲明,這樣外面就不能訪問了
let _types=types;
};
//將相同的方法或屬性放在原型鏈上,方便代碼的複用
Pet.say=function(){
return `hello!我叫:${this.name},我是一隻可愛的${this._types}`;
};
console.log(Pet.say());//hello!我叫:Pet,我是一隻可愛的undefined
二、繼承:子類繼承父類,就可擁有父類的屬性和方法//在js中利用對象冒充(父類構造函數去充當子類的屬性)的方式實現繼承
//方法1:在js中利用對象冒充(父類構造函數去充當子類的屬性)的方式實現繼承
//繼承
let Pet=function (name,types) {
this.name=name;
this.types=types;
};
let Dog=function(name,types,colors,age){
this.colors=colors;
this.age=age;
this.temp=Pet;//將Pet構造函數賦值給temp,充當Dog的子類
this.temp(name,types);//調用其構造函數並賦值
delete this.temp;//此時temp已經無用了,將其刪除
}
let taidi=new Dog("泰迪","小狗","土其色",2);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 2
//方法2:使用方法借用的方式實現繼承
let Pet=function (name,types) {
this.name=name;
this.types=types;
};
let Dog=function(name,types,colors,age){
//借用Pet的方法
//Pet.apply(this,[name,types]);
Pet.call(this,name,types);
this.colors=colors;
this.age=age;
}
let taidi=new Dog("泰迪","小狗","土其色",2);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 2
//方法3:最終,js採用了原型鏈繼承的方式
//採用了原型鏈繼承的方式
let Pet=function (name,types) {
this.name=name;
this.types=types;
};
//給Pet原型鏈上添加一個方法
Pet.prototype.say=function(){
return `hello!大家好我是smallzz`;
}
let Dog=function(name,types,colors,age){
//借用Pet的方法
//Pet.apply(this,[name,types]);
Pet.call(this,name,types);
this.colors=colors;
this.age=age;
};
//將Pet的構造函數放在Dog的原型鏈上
Dog.prototype=new Pet();
let taidi=new Dog("泰迪","小狗","土其色",2);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 2
console.log(taidi.say());//hello!大家好我是smallzz
方法4:ES6提供了extends關鍵字
//使用extends實現繼承
class Pet{
constructor(name,types){
this.name=name;
this.types=types;
}
say(){
return `hello!大家好我是smallzz`;
}
}
class Dog extends Pet{ //繼承Pet
constructor(name,types,colors,age){
super(name,types);//調用父類的構造器
this.colors=colors;
this.age=age;
}
}
let taidi=new Dog("泰迪","小狗","土其色",3);
console.log(taidi.name+" "+taidi.types+" "+taidi.colors+" "+taidi.age);//泰迪 小狗 土其色 3
console.log(taidi.say());//hello!大家好我是smallzz
三、多態:定義:同一操作用於不同的對象上,會產生不同的結果。js中的對象天生就是多態的
PS:方法借用