類的四種定義方法
阿新 • • 發佈:2018-11-11
// 工廠模式 function Car(name, color, price) { var tempcar = new Object; tempcar.name = name; tempcar.color = color; tempcar.price = price; tempcar.getCarInfo = function () { console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); } return tempcar; } var mycar = new Car('BMW', 'red', '100000'); mycar.getCarInfo(); 缺點:每次 new 一個物件的時候,都會重新建立一個 getCaeInfo() 函式; // 建構函式方式 function Car(name, color, price) { this.name = name; this.color = color; this.price = price; this.getCarInfo = function () { console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); } } var myCar = new Car('桑塔納', 'green', '123456'); myCar.getCarInfo(); 優點: 不用建立臨時物件; 不用返回臨時物件; 缺點:與‘工廠模式’相同,重複建立函式; // 原型方式 function Car(name, color, price) { Car.prototype.name = name; Car.prototype.color = color; Car.prototype.price = price; Car.prototype.getCarInfo = function () { console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); } } var myCar = new Car('蘭博基尼', 'red', '10000000000'); myCar.getCarInfo(); 優點: 解決了重複建立函式的問題; 可以使用 instanceof 檢驗型別 myCar instanceof Car // true 缺點: 多個例項建立的相同屬性指向同一塊記憶體; 例子: Car.prototype.drivers = ['Tim', 'Jone']; myCar.drivers.push('mike'); console.log(myCar.drivers); // ['Tim', 'Jone', 'mike'] // 動態原型方式(推薦) function Car(name, color, price, drivers) { this.name = name; this.color = color; this.price = price; this.drivers = drivers; } Car.prototype.getCarInfo = function () { console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); } var myCar = new Car('蘭博基尼', 'red', '10000000000', ['qaz', 'wsx']); myCar.drivers.push('mi'); console.log(myCar.drivers); // ["qaz", "wsx", "mi"] var myCar1 = new Car('蘭博基尼1', 'red1', '100000000001', ['qaz1', 'wsx1']); myCar1.drivers.push('mi1'); console.log(myCar1.drivers); // ["qaz1", "wsx1", "mi1"] 思想: 類的屬性 要隨例項物件動態改變; => 動態 類的方法 要隨原型保持不變;=> 原型