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';
}
愛它 - 這更有意義 –
爲什麼你要創建一個新的對象?這沒有必要。你做的和我在做的一樣,除非你是_always_檢查'options.name'是否存在,即使你剛剛確定它不存在。 – Cerbrus
@Cerbrus這是有道理的,如果有多個選項來檢查;它也更清晰,更清潔。 – JJJ