JavaScript는 단축 구문을 사용하여 객체를 생성합니다 [Ctrl A 모두 선택 참고: 외부 J를 도입해야 하는 경우 실행하려면 새로 고쳐야 합니다. ] 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/>"); }