<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> //直接创建实例,并为其添加属性 var person0 = new Object(); person0.name = "zhichao"; person0.age = 30 for (var txt in person0) { console.log("person0's " + txt + "=" + person0[txt]); /** * person0's name=zhichao * person0's age=30 */ } //使用对象literals构造对象 var person1 = { name: "yangys", age: 29 }; for (var txt in person1) { console.log("person1's " + txt + "=" + person1[txt]); /** * person1's name=yangys * person1's age=29 */ } //使用构造函数构造对象 function person2(name, age) { this.name = name; this.age = age; } var zhangmin = new person2("zhangmin", 28); for (var txt in zhangmin) { console.log("zhangmin's " + txt + "=" + zhangmin[txt]); /** * zhangmin's name=zhangmin * zhangmin's age=28 */ } //为已有对象添加新属性 person1.sex = "男"; person1.height = 174.5 for (var txt in person1) { console.log("person1's " + txt + "=" + person1[txt]); /** * person1's sex=男 * person1's height=174.5 */ } function person4(name, age) { this.name = name; this.age = age; //为自定义对象添加方法 this.walk = walk;//这句话是必须要的! function walk() { console.log(name + "is walking!"); } } var yangkejun = new person4("yangkejun", 64); yangkejun.walk(); /** * yangkejun is walking! */ </script> </head> <body> </body> </html>