關(guān)于javascript對(duì)類的一些理解
1:在javascript中,函數(shù)也是一種對(duì)象,所以他也可以有屬性和方法。
2:定義一個(gè)類,實(shí)際上是定義一個(gè)構(gòu)造函數(shù)。通常遵循的規(guī)范是函數(shù)名大寫,
但這個(gè)只是大家的一中習(xí)慣性的編程規(guī)范,不是必須的。當(dāng)然你也可以小
寫。
3:對(duì)象的屬性有以下幾種寫法:
a:直接在對(duì)象上添加,格式: xxobject.xxprop = 屬性值
xxobject表示某一個(gè)對(duì)象,xxprop表示要添加的新屬性。
例: var person = new Object();
person.name="sam";
alert(person.name); //值為sam;
上面的例子表示給person對(duì)象添加一個(gè)新的屬性name并輔值為sam.
b: 通過構(gòu)造函數(shù)定義類屬性.格式:
function classname(){
this.xxprop1 = xxvalue1;
this.xxprop2 = xxvalue2;
}
xxprop1 屬性1;
例:
function Person(){
this.name = 'sam';
this.sex = '男';
}
var person = new Person();
alert(person.name) //值為sam;
c: 通過構(gòu)造函數(shù)的prototype對(duì)象添加屬性 ,格式:Class.prototype.xxprop= value;
Class表示某構(gòu)造函數(shù),prototype是構(gòu)造函數(shù)對(duì)應(yīng)的prototype對(duì)象.每一個(gè)構(gòu)造函數(shù)
都有一個(gè)名位prototype的對(duì)象.
例:
function Person(){ };
Person.prototype.name = 'sam';
Person.prototype.sex = "男";
var person = new Person();
alert(person.name) //值為sam;
注意:用構(gòu)造函數(shù)體內(nèi)定義的屬性(如b: this.xxprop1=xxvalue1;) 與在函數(shù)的prototype
對(duì)象里添加屬性的方式有什么區(qū)別?
主要區(qū)別在于:構(gòu)造函數(shù)體內(nèi)定義的屬性每次new一個(gè)新的對(duì)象時(shí),都會(huì)在內(nèi)存中創(chuàng)建這些屬性
的副本,而prototype里添加的屬性則不會(huì),它們?cè)趦?nèi)存中始終只有一份.不會(huì)因?yàn)閷?duì)象的創(chuàng)建,
存在對(duì)分屬性的內(nèi)存空間.但是他們的訪問方式都是一樣的,都是通過對(duì)象名點(diǎn)屬性名的方式
(person.name).
d: 通過對(duì)象直接量的方式添加對(duì)象屬性.格式: var objectName={xxprop1:xxvalue,
xxprop2:xxvalue2};
我們知道javascript創(chuàng)建一個(gè)對(duì)象,有三種方式:
第一種:通過Object函數(shù)創(chuàng)建.如:var person = new Object();
然后通過上面a的方式加入屬性值如: person.name = 'sam';
第二種: 通過定義構(gòu)造函數(shù)來創(chuàng)建.如上b方式.如: person = new Person();
第三種方式:通過對(duì)象直接量創(chuàng)建. 比如:
var person = {name:'sam',sex:'man',age:18};
即:大括號(hào)內(nèi)寫入 屬性 冒號(hào) 值 ,即可.
posted on 2008-04-01 21:15 sam.chuan.yang 閱讀(310) 評(píng)論(2) 編輯 收藏 所屬分類: javascript 筆記