2012-11-19 29 views
0

考慮下面的代碼:原型時,是否可以將方法的結果分配給屬性?

function rectangle(x, y) { 
    this.width = x; 
    this.height = y; 
    this.calcArea = function() { 
     return (this.width * this.height); 
    }; 
} 

rectangle該對象具有兩個屬性(寬度和高度)和一個方法(油杉)。

我想另一個屬性添加到矩形對象:area。我將做到這一點通過原型方法,像這樣:

rectangle.prototype.area = function() {return this.calcArea();} 

現在想象一下,我們創建矩形的新實例:var r = new rectangle(2,3); 不幸的是,area是一種方法。要獲取正確的值,你必須調用r.area();

由於area應該是(語義上,至少)的屬性,而不是一個方法,是有辦法的calcArea()結果直接分配到r.area財產?

如果我改變原型,以這樣的:

rectangle.prototype.area = function() {this.area = this.calcArea();} 

我要叫r.area()一次,然後到r.area所有後續調用將是一個數字,根據需要。這並不壞,但並不完美。那麼有沒有更好的方法?

+1

東西已經佔到位置:http://stackoverflow.com/questions/812961/javascript-getters-and-setters-for-dummies但你需要忘記IE。 –

+1

爲什麼不加上this.area = x * y;在矩形(x,y)函數中? – alemangui

回答

2

矩形的區域被從其他屬性來計算,從矩形改變矩形。因此,區域不屬於原型,而是屬於每個實例。無論如何,在原型中擁有一個屬性都是毫無意義的,它會被Rectangle的每一個實例所遮蔽。雖然計算可以屬於原型,因爲它對每個矩形都是一樣的。

爲了讓你至少有一次來計算它的價值,就像你說的。您可以在Rectangle的構造函數中執行此計算,但最好將該方法留在原型中,因爲它不需要重複。

function Rectangle(x, y) { 
    this.width = x; 
    this.height = y; 
    this.area = this.calculateArea(); 
} 

Rectangle.prototype.calculateArea = function(){ 
    return this.width * this.height; 
} 

請記住,如果您在創建矩形後更改矩形尺寸,則不會更新此值。出於這個原因,我總是按需求計算它,因爲它更安全,除非這個屬性經常被調用並且性能是一個問題。

1

爲什麼不能在構造函數計算呢?

function rectangle(x, y) { 
    this.width = x; 
    this.height = y; 
    this.area = x*y; 
    .. 
} 

現在的問題,它不會來,如果你更新widthheight更新。在這種情況下,使用這個。

function rectangle(x, y) { 
    this.width = x; 
    this.height = y; 
    this.area = x*y; 
    this.updateWidth = function(w){ 
     this.width = w; 
     this.area = this.width*this.height; 
    } 
    this.updateHeight = function(h){ 
     this.height = h; 
     this.area = this.width*this.height; 
    } 
} 
相關問題