如何创建JavaScript对象
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Game</title> </head> <body> <script type="text/javascript"> //直接创建方法 // var student = new Object(); // student.name="冯潇颍"; // student.age="18"; // student.doHomework=function(){ // console.log(this.name+"正在做作业……"); // } // student.doHomework(); //初始化式 // var student={ // name:"冯潇颍", // age:"18", // doHomework:function(){ // console.log(this.name+"正在做作业。。。。") // } // } // student.doHomework(); //构造方式(可以方便的创建多个对象) // function Student(name,age){ // this.name=name; // this.age=age; // this.doHomework=function(){ // console.log(this.name+"正在做作业"); // } // } // var student = new Student("冯潇颍","18"); // student.doHomework(); //原型式(不方便创建多个对象:实现了自定义方法和构造方法的分离) // function Student(){} // Student.prototype.name="张皓"; // Student.prototype.age="18"; // Student.prototype.doHomework=function(){ // console.log(this.name+"正在打冯潇颍"); // } // var student = new Student(); // student.doHomework(); // student = new Student(); // student.name="冯潇颍"; // student.doHomework(); //混合式(构造函数式+原型式) function Student(name,age){ this.name=name; this.age=age; } Student.prototype.doHomework=function(){ console.log(this.name+"正在打人"); } var student = new Student("张皓","18"); student.doHomework(); </script> </body> </html>