標籤:his call blank show new color 對象 this 屬性
/**
* js實現繼承:
* 1.基於原型鏈的方式
* 2.基於偽造的方式
* 3.基於組合的方式
*/
一、基於原型鏈的方式
function Parent(){
this.pv = "parent";
}
Parent.prototype.showParentValue = function(){
console.log(this.pv);
}
function Child(){
this.cv = "child";
}
//讓Child的原型鏈指向Parent,也就等於完畢了一次繼承
Child.prototype = new Parent();
Child.prototype.showChildValue = function(){
console.log(this.cv);
}
var c = new Child();
c.showParentValue(); //parent
c.showChildValue(); //child
/**
*在使用原型鏈進行繼承時,應注意下面問題:
*1.不能在設定了原型鏈之後,再又一次為原型鏈賦值
*2.一定要在原型鏈賦值之後才幹加入或者覆蓋方法
*/
使用原型鏈繼承的缺點是:
1.無法從子類中調用父類的建構函式,
2.假設父類中存在參考型別。這個參考型別會加入到子類的原型中。假設一個對象改動了這個引用,其他對象的引用同一時候改動
所以一般都不會單純的使用原型鏈來實現繼承。
二、基於偽造的方式
function Parent(){
this.color = ["red","blue"];
}
function Child(){
//在Child中的this應該是指向Child的對象
//在調用Parent方法的時候,並且this又指向了Child,就等於是:this.color = ["red","blue"];
//也就等於在Child中有了this.color屬性,這樣也就變向的完畢了繼承
Parent.call(this);
//Parent(); 這樣的調用方式,僅僅是完畢了函數的調用。根本無法實現繼承
}
var c1 = new Child();
c1.color.push = "green";
console.log(c1.color); //red,blue,green
var c2 = new Child();
console.log(c2.color); //red,blue
//可是這依舊不太好,例如以下:
------------------------------------------------------------------------------
function Parent(name){
this.color = ["red","blue"];
this.name = name;
/*this.say = function(){
console.log(this.name);
}*/
}
Parent.prototype.say = function(){
console.log(this.name);
}
function Child(name,age){
/**
* 使用偽造的方式就能夠把子類的建構函式參數傳遞到父類中
* 存在問題:
* 1.因為使用的偽造方式。不會完畢Child的原型指向Parent,所以對Child來說say方法不存在
* 解決方式:
* 將這種方法放到Parent中,使用this來建立
* 可是這又引起前面提到的問題:
* 每一個Child對象都會有一個say,佔用空間。所以也不應單獨的使用偽造的方式實現繼承。
* 因此我們要使用組合的方式來解決問題
*/
this.age = age;
Parent.call(this,name);
}
var c1 = new Child("Leon",13);
var c2 = new Child("Ada",22);
console.log(c1.name+","+c1.age);
console.log(c2.name+","+c2.age);
三、基於組合的方式
組合的方式是:屬性通過偽造的方式實現。方法通過原型鏈的方式實現。
function Parent(name){
this.color = ["red","blue"];
this.name = name;
}
Parent.prototype.ps = function(){
console.log(this.name+",["+this.color+"]");
}
function Child(name,age){
this.age = age;
Parent.call(this,name);
}
Child.prototype = new Parent();
Child.prototype.say = function(){
console.log(this.name+","+this.age+",["+this.color+"]");
}
var c1 = new Child("Leon",22);
c1.color.push("green");
c1.say(); //Leon,22,[red,blue,green]
c1.ps(); //Leon,[red,blue,green]
var c2 = new Child("Ada",23);
c2.say(); //Ada,23,[red,blue]
c2.ps(); //Ada,[red,blue]
原創文章如轉載。請註明出處,本文首發於csdn網站:http://blog.csdn.net/magneto7/article/details/25010555
js:深入繼承