面向?qū)ο笪?/h2>

面向?qū)ο蟾呒?jí)二

  1. 總結(jié) PHP 里的面向?qū)ο蟆⒗^承方式
  2. 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>
  1. 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>
  1. 引用類型的特點(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>
  1. 原型繼承的缺點(diǎn)及解決方案


    image.png

    把父類的方法一個(gè)個(gè)扔到子類,這樣父類就沒(méi)有子類的方法了。.png

    用到的知識(shí)點(diǎn):


    image.png
  2. instanceof 作用:查看某個(gè)對(duì)象是否是某個(gè)類的實(shí)例

<script>
var arr1=[1,2,3];

alert(arr1 instanceof Object);
</script>
  1. 用繼承來(lái)實(shí)現(xiàn)拖拽實(shí)例

  2. 系統(tǒng)對(duì)象:宿主對(duì)象、內(nèi)置對(duì)象、本地對(duì)象


    image.png
  3. 繼承的優(yōu)勢(shì)(補(bǔ)充)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容