2014-06-16 42 views
-2

所以門,我的代碼,這樣的結構:Javascript ||與不確定對象的屬性

var player; 
function Player(lives) { 
    this.lives = lives; 
} 

function init() { 
    player = new Player(player.lives || 3); 
} 

init(); // Doesn't work, 3 lives 
player.lives--; 
init(); // Will work, 2 lives 
player.lives--; 
init(); // Will work, 1 lives 
player.lives--; 
init(); // Will work, 3 lives 

因此,有2個選項;

1:無論如何要做一個「新」功能,可以保持某些值?

2:有沒有更快的方法比這樣做:

function init() { 
    player = new Player((player == "undefined" ? 0 : player.lives) || 3) 
} 
+3

此問題似乎是脫離主題,因爲它需要代碼審查。 –

+0

「代碼審查」是什麼意思? – super

+1

http://codereview.stackexchange.com/ –

回答

1

更新:好吧,我的理解是:

  1. 你總是希望創建一個新的球員,即使你已經有一個(這對我來說似乎有點奇怪)

  2. 如果player.lives達到0,你想在3

答案再次啓動:

1:反正有做一個「新」功能,可以保持一定的值?

不是沒有將構造函數(「新」函數「)綁定到特定的對象實例,這會破壞具有構造函數的目的。你可能作爲一個可選參數傳入一個前一個對象,但我不會在這個級別做它,我會在構造函數外處理它。

但只是爲了完整性:

function Player(lives, player) { 
    this.lives = (player ? player.lives : lives) || lives; 
} 

有時你會看到這個版本,這我不是因爲臨時對象的粉絲:

function Player(lives, player) { 
    this.lives = (player || {lives: lives}).lives || lives; 
} 

無論哪種方式,您使用它是這樣的:

function init() { 
    player = new Player(3, player); 
} 

如果你沒有在第二個參數傳遞,或傳遞一個在這falsey,或者我t沒有錯,它沒有lives屬性,或者它不是假的,它有一個lives屬性,但該屬性是falsey,你將使用第一個參數。否則,它將是第二個參數的lives屬性。

2:有沒有更快的方法比這樣做:

不知道你的意思是「快」,但你可以相當簡潔:

function init() { 
    player = new Player(player ? (player.lives || 3) : 3); 
} 

或課程該臨時對象再次:

function init() { 
    player = new Player((player || {lives: 3}).lives || 3); 
} 
+0

K,但我說了一定的數值​​,那麼我的意思是我的數值應該被重新設定而不是,所以相當於player = new Player((!player?0:player.lives)|| 3) – super

+0

@Murplyx:Why每次都創建一個新玩家?如果你有任何其他的參考,他們會過時。但是,是的,如果你想每次都創建一個新玩家,那麼'player = new Player(player?player.lives:3);' –

+1

@Murplyx:注意:提防'x || 3',當'x'是一個可以有效地爲'0'的數字。 –