Open LeoWangJ opened 4 years ago
上一篇物件導向與構造函數(constructor)中提到構造函數,但由於構造函數創造出來的實例中方法與屬性無法共用。所以當如果有一個方法需要公用時,只能重複創建相同方法,這樣很耗費記憶體空間。而原型則是解決無法共用屬性的問題。
是儲存公用方法與屬性的地方,只需要創建一次即可使子類使用。
let Car = function(name,color,amount){ this.name = name this.color = color this.amount = amount } Car.prototype.tax = function(countryTax){ return this.amount * countryTax } let car1 = new Car('toyota','black',700000) let car2 = new Car('bmw','black',1400000) car1.tax(1.2) // 840000 car2.tax(1.3) // 1820000 car1.tax === car2.tax // true, 說明方法來自同一個地方
上一篇物件導向與構造函數(constructor)中提到構造函數,但由於構造函數創造出來的實例中方法與屬性無法共用。所以當如果有一個方法需要公用時,只能重複創建相同方法,這樣很耗費記憶體空間。而原型則是解決無法共用屬性的問題。
原型(prototype)
是儲存公用方法與屬性的地方,只需要創建一次即可使子類使用。
proto 是什麼 ?