經過 JavaScript,您可以定義並建立本身的對象。函數
建立新對象有兩種不一樣的方法:this
這個例子建立了對象的一個新實例,並向其添加了四個屬性:prototype
person=new Object(); person.firstname="Bill"; person.lastname="Gates"; person.age=56; person.eyecolor="blue";
替代語法(使用對象 literals):對象
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
本例使用函數來構造對象:ip
function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }
一旦您有了對象構造器,就能夠建立新的對象實例,就像這樣:get
var myFather=new person("Bill","Gates",56,"blue"); var myMother=new person("Steve","Jobs",48,"green");
您能夠經過爲對象賦值,向已有對象添加新屬性:it
假設 personObj 已存在 - 您能夠爲其添加這些新屬性:firstname、lastname、age 以及 eyecolor:io
person.firstname="Bill"; person.lastname="Gates"; person.age=56; person.eyecolor="blue"; x=person.firstname;
在以上代碼執行後,x 的值將是:ast
Bill
方法只不過是附加在對象上的函數。function
在構造器函數內部定義對象的方法:
function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.changeName=changeName; function changeName(name) { this.lastname=name; } }
changeName() 函數 name 的值賦給 person 的 lastname 屬性。
如今您能夠試一下:
myMother.changeName("Ballmer");
JavaScript 是面向對象的語言,但 JavaScript 不使用類。
在 JavaScript 中,不會建立類,也不會經過類來建立對象(就像在其餘面向對象的語言中那樣)。
JavaScript 基於 prototype,而不是基於類的。
JavaScript for...in 語句循環遍歷對象的屬性。
for (對象中的變量) { 要執行的代碼 }
註釋:for...in 循環中的代碼塊將針對每一個屬性執行一次。
循環遍歷對象的屬性:
var person={fname:"Bill",lname:"Gates",age:56}; for (x in person) { txt=txt + person[x]; }
來自於:http://www.w3school.com.cn/js/js_objects.asp