例如:创建一个文件的对象,文件有大小,文件有创建日期,文件可以移动
//(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("这个文件能移动。");
};