1. 程式人生 > 其它 >26.複習ES5建構函式繼承

26.複習ES5建構函式繼承

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <script> // 手機---父級建構函式 function Phone(brand, price) { this.brand = brand; this.price = price; }
Phone.prototype.change = function () { console.log("改變自己,改變全世界"); };
// 智慧手機---子級建構函式 function SmartPhone(brand, price, color, size) { // 繼承父類的一些方法及屬性,通過call方法改變this指向,讓Phone的this指向SmartPhoen裡面的this Phone.call(this, brand, price); this.color = color; this.size = size; }
// 設定子級建構函式的原型---讓SmartPhone的prototype指向Phone例項物件的__proto__ SmartPhone.prototype = new Phone(); //這裡不加()也可以 Chrome瀏覽器的[[prototype]]有時間瞭解一下,相當於__proto__,表示物件的應用關係! // 一般會做下面的一個校正,不做也可以 SmartPhone.prototype.construcuor = SmartPhone;
// 給SmartPhone原型上新增方法 SmartPhone.prototype.photo = function () { console.log("我可以拍照"); };
SmartPhone.prototype.playGame = function () { console.log("我可以玩遊戲!"); };
let apple = new SmartPhone("蘋果", "1299", "灰色", "5.5inch"); console.log(apple); </script> </body> </html>