javascript拾遺之對象

?? js是基于簡單的object-based paradigm設(shè)計的,每一個對象都是一些屬性的集合,每一個屬性是key:value之間的聯(lián)系。一個屬性的value可以是function,那么這個屬性就被稱為方法。除了瀏覽器預(yù)設(shè)的對象之外,你還可以自己定義對象。

在js里一個對象是一個獨(dú)立的實(shí)體,具有屬性(property)和類別(type).

varmyCar=newObject();

myCar.make='Ford';

myCar.model='Mustang';

myCar.year;//undefined

一個對象的聲明未初始化的屬性是undefined(and notnull).

一個對象有時也被稱為關(guān)聯(lián)數(shù)組,因?yàn)槊恳粋€屬性都是一種key到value的關(guān)聯(lián)。你可以通過[propertyName]訪問屬性;


在js里你可以通過定義構(gòu)造函數(shù)來定義對象

functionCar(make,model,year){

this.make=make;

this.model=model;

this.year=year;

}

var mycar = new Car('Eagle', 'Talon TSi', 1993);


functionEmployee(){

this.name='';

this.dept='general';

}

function Manager() {

Employee.call(this);

this.reports = [];

}

Manager.prototype = Object.create(Employee);

現(xiàn)在有一個"動物"對象的構(gòu)造函數(shù)。

function Animal(){

    this.species = "動物";

  }

還有一個"貓"對象的構(gòu)造函數(shù)。

function Cat(name,color){

    this.name = name;

    this.color = color;

  }

怎樣才能使"貓"繼承"動物"呢?

一、 構(gòu)造函數(shù)綁定

第一種方法也是最簡單的方法,使用call或apply方法,將父對象的構(gòu)造函數(shù)綁定在子對象上,即在子對象構(gòu)造函數(shù)中加一行:

  function Cat(name,color){

Animal.apply(this, arguments);

    this.name = name;

    this.color = color;

  }

  var cat1 = new Cat("大毛","黃色");

  alert(cat1.species); // 動物

二、 prototype模式

第二種方法更常見,使用prototype屬性。

如果"貓"的prototype對象,指向一個Animal的實(shí)例,那么所有"貓"的實(shí)例,就能繼承Animal了。

  Cat.prototype = new Animal();

  Cat.prototype.constructor = Cat;

  var cat1 = new Cat("大毛","黃色");

  alert(cat1.species); // 動物

代碼的第一行,我們將Cat的prototype對象指向一個Animal的實(shí)例。

  Cat.prototype = new Animal();

它相當(dāng)于完全刪除了prototype 對象原先的值,然后賦予一個新值。但是,第二行又是什么意思呢?

  Cat.prototype.constructor = Cat;

原來,任何一個prototype對象都有一個constructor屬性,指向它的構(gòu)造函數(shù)。如果沒有"Cat.prototype = new

Animal();"這一行,Cat.prototype.constructor是指向Cat的;加了這一行以后,Cat.prototype.constructor指向Animal。

 alert(Cat.prototype.constructor == Animal); //true

更重要的是,每一個實(shí)例也有一個constructor屬性,默認(rèn)調(diào)用prototype對象的constructor屬性。

  alert(cat1.constructor == Cat.prototype.constructor); // true

因此,在運(yùn)行"Cat.prototype = new Animal();"這一行之后,cat1.constructor也指向Animal!

  alert(cat1.constructor == Animal); // true

這顯然會導(dǎo)致繼承鏈的紊亂(cat1明明是用構(gòu)造函數(shù)Cat生成的),因此我們必須手動糾正,將Cat.prototype對象的constructor值改為Cat。這就是第二行的意思。

這是很重要的一點(diǎn),編程時務(wù)必要遵守。下文都遵循這一點(diǎn),即如果替換了prototype對象,

  o.prototype = {};

那么,下一步必然是為新的prototype對象加上constructor屬性,并將這個屬性指回原來的構(gòu)造函數(shù)。

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

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

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