2014-10-27 160 views
0

使用下面的物體作爲一個例子創建對象並設置屬性

var CarAd = function(car){ 
this.year = car.year; 
this.model = car.model; 
this.make = car.make; 
this.formattedDescription = function(){ 
    return "this is a " + this.year + " " + this.make + " " + this.model; 
} 
} 

我想,對於formattedDescription價值是可利用的實例化對象,但因爲它的立場,formattedDescription()當然會,不執行直到它被調用。這將如何重構?

+0

請不要將解決方案添加到您的曲目中estion。您可以發佈一個單獨的答案,然後從您的問題中刪除解決方案。你可以,但不必接受你的答案。 – 2014-10-27 17:54:34

回答

0

我不知道它是否是hacky,但可以自動調用該函數並將其值賦給formattedDescription。

var CarAd = function(car){ 
this.year = car.year; 
this.model = car.model; 
this.make = car.make; 
this.formattedDescription = (function(){ 
    return "this is a " + this.year + " " + this.make + " " + this.model; 
})() 
} 

編輯......這樣感覺更自然:

var CarAd = function(car){ 
this.year = car.year; 
this.model = car.model; 
this.make = car.make; 
function createFormattedDescription() { 
    return "this is a " + this.year + " " + this.make + " " + this.model; 
}; 
this.formattedDescription = createFormattedDescription(); 
} 
+0

雖然我不得不做一個小小的改變,因爲它看起來在annon自我執行的func裏是'this'不可訪問的。 – 2014-10-27 17:44:41

+0

你確實提到他看起來有點不好意思。我想知道,是否有更合適的方法創建一個類,其中實例已經格式化了數據,類似於具有getter和setter的屬性? – 2014-10-27 17:49:16

+0

謝謝@MarkHollas。我改變了它,以便它使用實際(私人)功能。至少這感覺好多了:) – 2014-10-27 17:56:53

0

使this.formattedDescription像一個自我執行的功能:

this.formattedDescription = (function(){ 
    return "this is a " + this.year + " " + this.make + " " + this.model; 
})(); 
0

它可以是如此簡單:

var makecar = function(year, model, make){ 
    return { 
     year: year, 
     model: model, 
     make: make, 
     description: "this is a " + year + " " + make + " " + model 
    }; 
};