JavaScript创建对象的两种方法和遍历对象的属性
生活随笔
收集整理的這篇文章主要介紹了
JavaScript创建对象的两种方法和遍历对象的属性
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
創建新對象有兩種不同的方法:
- 定義并創建對象的實例
- 使用函數來定義對象,然后創建新的對象實例
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;
} ?
轉載于:https://www.cnblogs.com/halao/p/7678102.html
總結
以上是生活随笔為你收集整理的JavaScript创建对象的两种方法和遍历对象的属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 萌男换房型
- 下一篇: 春江花月夜电影啥时候播出?