2015-03-31 93 views
4

我正在使用Easel JS開發一個項目。開闢了畫架文件的代碼的第一行讓我感到困惑:|| {}在JavaScript中表示什麼?

this.createjs = this.createjs||{}; 

我知道,當你設置你的畫布,或者例如,創建一個位圖添加到畫布createjs被調用。但我不明白這一行的語法 - 將this.createjs或(我猜是)將一個空白對象賦給this.createjs?

+0

如果this.createjs對象不存在初始化this.createjs作爲對象... ...是什麼意思.. – 2015-03-31 10:21:25

+0

這意味着:如果this.createjs不是undefined,則使用this.createj否則使用空對象。 – 2015-03-31 10:22:06

+0

如果this.createjs是falsy(undefined,false等),它將被空對象替換。 – biera 2015-03-31 10:22:26

回答

6
this.createjs = this.createjs||{}; 

如果this.createjs不可/任何falsy值,那麼你要分配{}空對象this.createjs

它更像,

var a, 
    b; 

b = a || 5; 

由於a是不是有目前,5將被分配到b任何價值。

+1

完美,這是一個非常明確的答案。謝謝! – unaesthetic 2015-03-31 10:26:41

2

正確。這確保如果this.createjs尚不存在,則爲其分配空的對象。 ||是一個或運算符 - 如果this.createjs在左側評估爲falsy,它將分配右側。

1

||表示or。 在這方面意味着this.createjs等於如果存在/不爲null /規定this.createjs其他方式{}

2
this.createjs = this.createjs||{}; 

如果this.createjs是falsy,this.createjs將是一個新的空對象

你可以有取代它通過

if (!this.createjs){ 
    this.createjs = {}; 
}