幾種構造對象的方法
阿新 • • 發佈:2018-03-08
rip call har gets 創建 get post set ret
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script> 7 //1.利用內置構造函數的方式來創建對象 8 var zyb = new Object(); 9 zyb.name = "綠波"; 10 zyb.age = 40; 11 console.log(zyb);12 13 //2.利用工廠模式 14 function getStu(name,age) { 15 var stu = new Object(); 16 stu.name = name; 17 stu.age = age; 18 return stu; 19 } 20 var cc = getStu("程胖",16); 21 console.log(cc); 22 23 //3.自定義構造函數 24 function getBoy(name,age) { 25 this.name = name; 26 this.age = age; 27 this.yao = function () { 28 console.log("跟我龜丞相,一起搖:黑馬亂不亂,龜爺說了算"); 29 } 30 } 31 var lmg = new getBoy("鎮樓神龜",9000); 32 console.log(lmg);33 lmg.yao(); 34 35 //4.在使用內置構造方法的同時,初始化 36 var lcw = new Object( 37 { 38 name:"梁朝偉", 39 age:16, 40 say:function () { 41 console.log(this.name); 42 } 43 } 44 ); 45 console.log(lcw); 46 lcw.say(); 47 48 //5.使用對象的字面量來創建對象/可以初始化 49 var mpy = { 50 name:"媽賣批", 51 age:56, 52 say:function () { 53 console.log(this.name); 54 } 55 }; 56 var res = Object.prototype.toString.call(mpy); 57 console.log(res);//object Object 58 console.log(mpy); 59 mpy.say(); 60 </script> 61 </head> 62 <body> 63 64 </body> 65 </html>
幾種構造對象的方法