2013-01-09 81 views
0

我想設置一個默認的「小」,如果沒有選項被傳遞到我的構造函數對象:爲什麼設置參數的默認值不工作在我的JavaScript?

var Plan = function(options){ 
    this.name = options.name || 'small'; 
} 

,但是當我這樣做:

var smallPlan = new Plan(); 

console.log(smallPlan.name); 

我得到Uncaught TypeError: Cannot read property 'name' of undefined

什麼我做錯了嗎?這不是在JavaScript中設置默認參數值的慣用方法嗎?

回答

9

,而不是通過代碼複雜,以檢查是否選擇和名稱是存在的,檢查,看看是否定義對象,如果沒有,將其設置爲一個空的對象。

var Plan = function(options){ 
    options = options || {}; 
    this.name = options.name || 'small'; 
} 
+0

愛它 - 這更有意義 –

+0

爲什麼你要創建一個新的對象?這沒有必要。你做的和我在做的一樣,除非你是_always_檢查'options.name'是否存在,即使你剛剛確定它不存在。 – Cerbrus

+0

@Cerbrus這是有道理的,如果有多個選項來檢查;它也更清晰,更清潔。 – JJJ

4

options未定義。如果options不存在,則不能訪問options.name

如果你想檢查的不僅僅是一個屬性的更多,我建議是這樣的:

var Plan = function(options){ 
    // Set defaults 
    this.name = 'foo'; 
    this.title = 'bar'; 
    this.something = 'even more stuff'; 
    if(options){ // If options exists, override defaults 
     this.name = options.name || this.name; 
     this.title = options.title || this.title; 
     this.something = options.something || this.something; 
    } 
} 

否則,我想嘗試這樣的:

var Plan = function(options){ 
    this.name = options ? options.name || 'small' : `small`; 
} 

這是一個有點難看,但是您必須檢查options是否存在,並且options是否具有name屬性。

這樣做是:

if(options){ 
    if(options.name){ 
     this.name = options.name; 
    } else { 
     this.name = 'small'; 
    } 
} else { 
    this.name = 'small'; 
} 
相關問題