javascript 中的 ||{} 是什么意思?

What does ||{} mean in javascript?

我正在使用 Easel JS 开发一个项目。打开 Easel 文件,第一行代码让我感到困惑:

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

我知道当您设置 canvas 或创建位图以添加到 canvas 时会调用 createjs。但我不明白这一行的语法 - 将 this.createjs 或(我猜是)一个空白对象分配给 this.createjs?

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

如果 this.createjs 不可用/任何 falsy 值,那么您正在将 {} 空对象分配给 this.createjs

更像是,

var a, 
    b;

b = a || 5;

由于a目前没有任何价值,5将被分配给b

正确。这确保如果 this.createjs 不存在,则为其分配一个空对象。 || 是一个或运算符 - 如果左侧的 this.createjs 计算为 falsy,它将分配给右侧。

||表示or。 在那种情况下意味着 this.createjs 等于 if exists/not null/defined this.createjs 其他方式 {}

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

如果this.createjs是假的,this.createjs将是一个新的空对象

您可以将其替换为

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