1. 程式人生 > 其它 >js建立物件

js建立物件

//字面量 json var student={ id:10001, name:"張三", scores:[ {subject:"html",score:90}, {subject:"JS", score:90} ] }
//function function Student(id,name){ this.id=id; this.name=name; this.scores=[ {subject:"html",score:90}, {subject:"JS", score:90} ] } Student.prototype.sex="男" Student.prototype.eat=function(food){ console.log("吃"+food) } //擴充套件 var stu=new Student(1000,"張三"); stu.eat(""); console.log(stu.sex)
//Object var stu2=new Object(); stu2.id=1000; stu2.name="張三"; stu2.scores=[ {subject:"html",score:90}, {subject:"JS", score:90} ]
function Student(id,name){ this.id=id; this.name=name; this.scores=[ {subject:"html",score:90}, {subject:"JS", score:90} ], this.eat=function(food){ console.log("吃"+food) return this //返回值 }, this.sleep=function(){ console.log("睡") return this //返回值 } } var stu=new Student(1001,"張三"); stu.eat("").sleep().eat("").sleep();//鏈式程式設計