JS创建对象多种方法

例如:创建一个文件的对象,文件有大小,文件有创建日期,文件可以移动

 //(1)使用函数兼new Object方法创建
           function creatFile(space,creattime){
               var file=new Object();
               file.space=space;
               file.creattime=creattime;
               file.move=function (){
                   console.log("这个文件能移动。");
               };
               return file;
           }
           var file1=creatFile("2G","2016-9-14");
           console.log(file1.space);
           console.log(file1.creattime);
           file1.move();
         //(2)使用自定义方式创建
         function CreatFile(space,creattime){
             this.space=space;
             this.creattime=creattime;
             this.move=function (){
                 console.log("这个文件能移动。");
             }
         }
        var file1=new CreatFile("2G","2016-9-14");
        console.log(file1.space);
        console.log(file1.creattime);
        file1.move();
          //(3)使用字面量方式创建对象
          var file={
              space:"2G",
              creattime:"2016-9-13",
              move:function (){
                  console.log("这个文件能移动");
              }
          }
          console.log(file.space);
          console.log(file.creattime);
          file.move();
            //(4)使用JSON方式
             var file={
                    "space":"2G",
                    "creattime":"2016-9-13",
                    "move":function (){
                        console.log("这个文件能移动");
                    }
                }
                console.log(file.space);
                console.log(file["creattime"]);
                file["move"]();

 //(5)直接使用new Object()创建

      var file=new Object();

file.space="1G";

file.creatTime="2015-9-10";

 file.move=function (){
                   console.log("这个文件能移动。");
               };


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值