面向?qū)ο蟾呒?jí)二
- 總結(jié) PHP 里的面向?qū)ο蟆⒗^承方式
- JS 里的繼承方式
<script>
function Person(name, sex)
{
this.name=name;
this.sex=sex;
}
Person.prototype.showName=function ()
{
alert(this.name);
};
Person.prototype.showSex=function ()
{
alert(this.sex);
};
//-------------------------------------
function Worker(name, sex, job)
{
//this->new出來(lái)的Worker對(duì)象
//構(gòu)造函數(shù)偽裝 調(diào)用父級(jí)的構(gòu)造函數(shù)——為了繼承屬性
Person.call(this, name, sex);
this.job=job;
}
//通過(guò)原型來(lái)繼承父級(jí)的方法
Worker.prototype=Person.prototype;
Worker.prototype.showJob=function ()
{
alert(this.job);
};
var oW1=new Worker('blue', '男', '打雜的');
oW1.showJob();
</script>
-
call(構(gòu)造函數(shù)偽裝) 和 prototype(原型鏈)
原型鏈.png
<script>
function Person(name, sex)
{
this.name=name;
this.sex=sex;
}
Person.prototype.showName=function ()
{
alert(this.name);
};
Person.prototype.showSex=function ()
{
alert(this.sex);
};
//-------------------------------------
function Worker(name, sex, job)
{
//this->new出來(lái)的Worker對(duì)象
//構(gòu)造函數(shù)偽裝 調(diào)用父級(jí)的構(gòu)造函數(shù)——為了繼承屬性
Person.call(this, name, sex);
this.job=job;
}
//原型鏈 通過(guò)原型來(lái)繼承父級(jí)的方法
//Worker.prototype=Person.prototype;
for(var i in Person.prototype)
{
Worker.prototype[i]=Person.prototype[i];
}
Worker.prototype.showJob=function ()
{
alert(this.job);
};
var oP=new Person('blue', '男');
var oW=new Worker('blue', '男', '打雜的');
oP.showName();
oP.showSex();
oW.showName();
oW.showSex();
oW.showJob();
</script>
-
引用類型的特點(diǎn)
image.png
arr1->arr2 內(nèi)存區(qū)域地址
<script>
var arr1=[1,2,3];
var arr2=arr1;
arr2.push(4);
alert('1:'+arr1); //1234
alert('2:'+arr2); //1234
</script>
<script>
var arr1=[1,2,3];
var arr2=[];
for(var i in arr1) //一份份復(fù)制
{
arr2[i]=arr1[i];
}
arr2.push(4);
alert('1:'+arr1); //1:123
alert('2:'+arr2); //2:1234
</script>
-
原型繼承的缺點(diǎn)及解決方案
image.png
把父類的方法一個(gè)個(gè)扔到子類,這樣父類就沒(méi)有子類的方法了。.png
用到的知識(shí)點(diǎn):
image.png instanceof 作用:查看某個(gè)對(duì)象是否是某個(gè)類的實(shí)例
<script>
var arr1=[1,2,3];
alert(arr1 instanceof Object);
</script>
用繼承來(lái)實(shí)現(xiàn)拖拽實(shí)例
-
系統(tǒng)對(duì)象:宿主對(duì)象、內(nèi)置對(duì)象、本地對(duì)象
image.png 繼承的優(yōu)勢(shì)(補(bǔ)充)





