定義一個函數做的兩件事:
1: 實例化一個Function對象;
2: 實例化一個Object對象,並給該函數擴展prototype屬性指向這個構造函數
大致過程如圖所示:
每一種引用類型(函數,對象,數組)都有__proto__屬性,並且其__proto__屬性指向其構造模板的prototype(原型對象)。
函數比較特殊,定義一個函數,分為上述兩個步驟。
驗證:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> //定義構造函數 function Student(n,a){ this.name = n; this.age = a; } //原型對象中加入方法 Student.prototype.sayHi = function(){ console.log("hello"); } //實例化對象 var stu = new Student("xiaoming",20); </script> </body> </html>