1:在javascript中,函數(shù)也是一種對象,所以他也可以有屬性和方法。
2:定義一個類,實際上是定義一個構(gòu)造函數(shù)。通常遵循的規(guī)范是函數(shù)名大寫,
但這個只是大家的一中習慣性的編程規(guī)范,不是必須的。當然你也可以小
寫。
3:對象的屬性有以下幾種寫法:
?。幔褐苯釉趯ο笊咸砑樱袷剑骸xobject.xxprop = 屬性值
xxobject表示某一個對象,xxprop表示要添加的新屬性。
例: var person = new Object();
person.name="sam";
alert(person.name); //值為sam;
上面的例子表示給person對象添加一個新的屬性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對象添加屬性 ,格式:Class.prototype.xxprop= value;
Class表示某構(gòu)造函數(shù),prototype是構(gòu)造函數(shù)對應的prototype對象.每一個構(gòu)造函數(shù)
都有一個名位prototype的對象.
例:
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
對象里添加屬性的方式有什么區(qū)別?
主要區(qū)別在于:構(gòu)造函數(shù)體內(nèi)定義的屬性每次new一個新的對象時,都會在內(nèi)存中創(chuàng)建這些屬性
的副本,而prototype里添加的屬性則不會,它們在內(nèi)存中始終只有一份.不會因為對象的創(chuàng)建,
存在對分屬性的內(nèi)存空間.但是他們的訪問方式都是一樣的,都是通過對象名點屬性名的方式
(person.name).
d: 通過對象直接量的方式添加對象屬性.格式: var objectName={xxprop1:xxvalue,
xxprop2:xxvalue2};
我們知道javascript創(chuàng)建一個對象,有三種方式:
第一種:通過Object函數(shù)創(chuàng)建.如:var person = new Object();
然后通過上面a的方式加入屬性值如: person.name = 'sam';
第二種: 通過定義構(gòu)造函數(shù)來創(chuàng)建.如上b方式.如: person = new Person();
第三種方式:通過對象直接量創(chuàng)建. 比如:
var person = {name:'sam',sex:'man',age:18};
即:大括號內(nèi)寫入 屬性 冒號 值 ,即可.