JavaScript 使用简略语法创建对象 window.onload = function(){ AppendMembersToObject(); SimpleSyntaxToCreateObject(); } function AppendMembersToObject() { var testName = "AppendMembersToObject"; WriteStart(testName); // 创建一个对象 var person = new Object(); // 给对象添加属性(public) person.Name = "lipei"; person.Sex = "boy"; person.Age = "24"; // 给对象添加方法(public) person.toString = function(){ //此处用person或this都可以,此时this指代person对象。 return str = "Name:" + this.Name + ",Sex:" + this.Sex + ",Age:" + this.Age; } WriteLine("person.Name : " + person.Name); WriteLine("person.toString() : " + person.toString()); WriteEnd(); /* 根据结果可知:JavaScript 中可在对象创建后,为对象添加成员(属性、方法等)。 */ } function SimpleSyntaxToCreateObject() { var testName = "SimpleSyntaxToCreateObject"; WriteStart(testName); // 使用简略语法创建对象 var computer = { Cpu : "酷睿2P系列", MainBoard : "华硕ER", Keyboard : "双飞燕", toString : function(){ return str = "Cpu:" + this.Cpu + ",MainBoard:" + this.MainBoard + ",Keyboard:" + this.Keyboard; } }; WriteLine("computer.MainBoard : " + computer.MainBoard); WriteLine("computer.toString() : " + computer.toString()); WriteEnd(testName); /* 根据结果可知:JavaScript简略语法可只能识别变量冒号后的类型,并据此定义变量的类型。 */ } /*************************Test Tools**************************/ function WriteLine(str) { document.write(str + "<br>"); } function WriteStart(str) { WriteLine("TEST : " + str + "<br>"); } function WriteEnd() { WriteLine("<br><hr/>"); } [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]