ES5/ES6中的類與繼承對比
阿新 • • 發佈:2018-12-03
ES5中的類和靜態方法
function Persion(name,age) { //建構函式裡面的方法和屬性 this.name = name; this.age = age; this.getInfo = function(){ console.log(`姓名:${this.name}---年齡:${this.age}`) } } //原型鏈上的屬性和方法可以被多個例項共享 Persion.prototype.sex = '男'; Persion.prototype.user = function(){ console.log(`${this.name}---${this.age}---${this.sex}`) } //靜態方法 Persion.address=function(){ console.log('靜態方法') } //靜態方法直接呼叫 Persion.address(); //例項化建構函式 var per1 = new Persion('star','24'); var per2 = new Persion('xiaohong','23'); //例項化呼叫 per1.getInfo(); per2.getInfo(); per1.user(); per2.user();
結果:
ES5繼承
/*
*組合繼承:原型鏈+物件冒充 *物件冒充繼承:沒法繼承原型鏈上面的屬性和方法,例項化子類的時候可以給父類傳參 *原型鏈繼承:可以繼承建構函式裡面以及原型鏈上面的屬性和方法,但是例項化子類的時候無法給父類傳參 兩者相輔相成,可以實現大多數情況下的繼承 */ function Persion(name,age){ this.name = name; this.age = age; this.getInfo = function(){ console.log(`姓名:${this.name}---年齡:${this.age}`) } } Persion.prototype.sex = '男'; Persion.prototype.user = function(){ console.log(`${this.name}---${this.age}---${this.sex}`) } function Thing(name,age){ //物件冒充繼承 Persion.call(this,name,age) } //原型鏈繼承 Thing.prototype = new Persion(); //可以給父類傳值 var per1 = new Thing('star',20); per1.getInfo(); //繼承建構函式的方法與屬性 per1.user();
結果:
ES6中的類和靜態方法
class Persion{ constructor(name,age){ //類的建構函式,例項化的時候執行 this.name = name; this.age = age; } getName(){ console.log(this.name) } setName(name){ this.name = name; } static run(){ //靜態方法 console.log('這是一個靜態方法,用static標記') } } Persion.address = '這是一個靜態屬性'; //靜態方法與屬性直接呼叫 Persion.run(); console.log(Persion.address) //例項化 var per1 = new Persion('star','24'); per1.getName(); per1.setName('xiaohong'); per1.getName();
結果:
ES6中的繼承
class Persion{
constructor(name,age){
this.name = name;
this.age = age;
}
getInfo(){
console.log(`姓名:${this.name}---年齡:${this.age}`)
}
}
//通過extends繼承類
class Per extends Persion{
constructor(name,age,sex){
super(name,age); //例項化子類的時候把資料傳遞給父類
this.sex = sex;
}
getSex(){
console.log(this.sex);
}
}
var per1 = new Per('star','24','男');
//繼承父類的方法
per1.getInfo();
per1.getSex();
結果:
ES6的單例模式
//模擬連線資料庫,只需要連線一次就好
class DB{
static getInstance(){ //通過靜態方法實現單例模式
if(!DB.instance){//自定義一個屬性用於記錄,第二次進來不再例項化
DB.instance = new DB(); //例項化
}
return DB.instance;
}
constructor(){
//例項化的時候觸發建構函式,連線資料庫
this.connect();
}
connect(){
console.log('連線資料庫');
}
find(){
console.log('查詢資料庫');
}
}
var db1 = DB.getInstance();
var db2 = DB.getInstance();
db1.find();
db2.find();
結果: