JavaScript建立類的四種方式
阿新 • • 發佈:2021-01-01
類的四種定義方法
1.工廠模式
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() 函式;
2. 建構函式方式
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();
優點:
-
不用建立臨時物件;
-
不用返回臨時物件;
缺點:與‘工廠模式’相同,重複建立函式;
3.原型方式
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']
4.動態原型方式(推薦)
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"]