1. 程式人生 > >15-自定義物件(建構函式)

15-自定義物件(建構函式)

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 <script>
 9 
10     //需求:多個自定義物件。
11     //缺點:程式碼冗餘,方式比較low。當我們建立空白物件的時候:new Object();
12     //利用建構函式自定義物件。
13 
14     var stu1 = new
Student("王五"); 15 var stu2 = new Student("趙六"); 16 17 console.log(stu1); 18 stu1.sayHi(); 19 20 console.log(stu2); 21 stu2.sayHi(); 22 23 // console.log(typeof stu1); 24 // console.log(typeof stu2); 25 26 //建立一個建構函式 27 function Student(name){ 28 //建構函式中的物件指的是this。
29 this.name = name; 30 this.sayHi = function () { 31 console.log(this.name+"說:大家好!"); 32 } 33 } 34 35 36 </script> 37 </body> 38 </html>