標籤:fat func last dem ack blog hang for font
建立新對象有兩種不同的方法:
- 定義並建立對象的執行個體
- 使用函數來定義對象,然後建立新的對象執行個體
1.定義並建立對象的執行個體
var person=new Object();person.firstname="John";person.lastname="Doe";person.age=50;person.eyecolor="blue";
或者
var person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
2.使用函數來定義對象,然後建立新的對象執行個體
function person(firstname,lastname,age,eyecolor){ this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor;}var myFather=new person("John","Doe",50,"blue");
myFather.hobby = "pingpang";//添加屬性
把方法添加到 JavaScript 對象
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; }}myMother=new person("Sally","Rally",48,"green");myMother.changeName("Doe");document.write(myMother.lastname);//輸出Doe
遍曆JavaScript對象的屬性
function myFunction(){ var x; var txt=""; var person={fname:"Bill",lname:"Gates",age:56}; for (x in person){ txt=txt + person[x]; } document.getElementById("demo").innerHTML=txt;}
JavaScript建立對象的兩種方法和遍曆對象的屬性