JavaScript面向对象之对象的声明、遍历和存储

一、对象的声明方式

1. 字面式(json格式)声明对象

var obj={
   属性名:属性值,
   方法名:function(){
      //函数执行体
   }
}
 

2. new 操作符+Object 声明对象

var obj=new Object();
obj.属性名=属性值;
obj.方法名=function(){
   //函数执行体
}
 

3. 构造函数声明对象

function test([参数列表]){
   this.属性名=属性值;
   this.方法名=function(){
      //函数执行体
   }
}
var obj=new test(参数);
 

4. 工厂方式声明对象

function createObject(nam,age){
   var obj=new Object();
   obj.name=name;
   obj.age=age;
   obj.run=function(){
      return this.name+this.age
   };
   return obj;
}
var obj1=createObject(‘zhangsan’,100);
var obj2=createObject(‘lisi’,200);
 

5. 原型模式声明对象

function test(){
   test.prototype.属性名=属性值;
   test.prototype.方法名=function(){
      //函数执行体
   }
}
var obj=new test();
 

6. 混合模式声明对象

function test(参 1,参 2){
   this.属性名 1=参 1;
   this.属性名 2=参 2;
}
test.prototype.方法名=function(){
   //执行代码
}
var obj=new test(参 1,参 2);

 

二、对象的遍历

  • for-in是为遍历对象而设计的,不适用于遍历数组。

  • 遍历数组的缺点:数组的下标index值是数字,for-in遍历的index值"0","1","2"等是字符串

var obj={
    name:"Zhangsan",
    age:"18",
    action:function(){
        alert("Hello!");
    }
}
for (var i in obj){
    console.log(i);    //控制台依次显示:name  age  action
}
for (var i in obj){
    console.log(obj[i]);    //控制台依次显示:Zhangsan  18  ƒ (){alert("Hello!");}
            alert("Hello!");
        }
}

 

三、对象的存储

var obj={}
    obj.name="Zhangsan";
    obj.age="18";
    obj.action=function(){
        alert("Hello!");
    }
 

猜你喜欢

转载自www.cnblogs.com/Leophen/p/11132481.html