码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript创建对象的两种方法和遍历对象的属性

时间:2017-10-16 19:21:20      阅读:166      评论:0      收藏:0      [点我收藏+]

标签: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创建对象的两种方法和遍历对象的属性

标签:fat   func   last   dem   ack   blog   hang   for   font   

原文地址:http://www.cnblogs.com/halao/p/7678102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!