1. 程式人生 > 其它 >JavaScript 建構函式

JavaScript 建構函式

# 建構函式的使用

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7   <title>Document</title>
 8
<script> 9 // 建構函式的執行流程 10 // 1立刻建立一個函式物件 11 // 2將新建的物件設定為函式中的this 12 // 3逐行執行函式中的程式碼 13 // 4將新建的物件作為返回值返回 14 // 建構函式就是類 15 function Person(name,age) { 16 this.name = name 17 this.age = age 18 19 } 20 const fun1 = new Person('孫悟空',23) 21 console.log(fun1.name);
22 console.log(fun1 instanceof Person); // 判斷一個例項是否是屬於該建構函式(類) 23 </script> 24 </head> 25 <body> 26 27 </body> 28 </html>