1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>JS三种创建构造函数方式</title> 6 </head> 7 <body> 8 </body> 9 <script> 10 //系统自带构造函数 11 var computer = new Object(); 12 computer.color = "black"; 13 computer.weight = "5kg"; 14 computer.brand = "lenovo"; 15 computer.watchMovie = function() { 16 console.log("看电影") 17 }; 18 computer.coding = function() { 19 console.log("敲代码") 20 }; 21 console.log(computer.color); 22 console.log(computer.weight); 23 console.log(computer.brand); 24 computer.watchMovie(); 25 computer.coding(); 26 27 console.log("--------------------"); 28 //自定义构造函数 29 function Computer(color,weight,brand) { 30 this.color = color; 31 this.weight = weight; 32 this.brand = brand; 33 this.watchMovie = function() { 34 console.log("看电影") 35 }; 36 this.coding = function() { 37 console.log("敲代码") 38 }; 39 } 40 var cp = new Computer("white","3kg","xiaomi"); 41 console.log(cp.color); 42 console.log(cp.weight); 43 console.log(cp.brand); 44 cp.watchMovie(); 45 cp.coding(); 46 47 console.log("--------------------"); 48 //字面量方式创建构造函数 49 cp2 = { 50 color: "grey", 51 weight: "6kg", 52 brand: "hp", 53 watchMovie: function() { 54 console.log("看电影"); 55 }, 56 play: function() { 57 console.log("玩游戏"); 58 } 59 }; 60 console.log(cp2.color); 61 console.log(cp2.weight); 62 console.log(cp2.brand); 63 cp2.watchMovie(); 64 cp2.play(); 65 </script 66 </html>