我需要根据参数值将两个标志 canPlayLive
和 isSubscribed
设置为 true
或 false
创建对象时发送。
基本上,当传递 null
undefined
''
时,我希望标志位于 false
上,否则位于 >true
.
使用以下代码标志始终为 true
。
我在这里做错了什么?
function MyStation(id, chId, name, hdImg, subscribedFlag, liveEntryId, liveUrl, timeLists) {
this.id = id;
this.dataId = chId;
this.name = name;
this.imageUrl = hdImg;
this.subscribedFlag = subscribedFlag;
this.liveEntryId = liveEntryId === null || undefined || '' ? null : liveEntryId;
this.liveUrl = liveUrl === null || undefined || '' ? null : liveUrl;
this.timeLists = timeLists;
this.canPlayLive = this.liveUrl === null || undefined || '' ? false : true;
this.isSubscribed = subscribedFlag == 0 ? false : true;
}
var test = new MyStation(
0,
'x123',
'foo',
'url',
0,
null,
'',
[]
);
console.log(test);
最佳答案
由于 canPlayLive 依赖于 liveUrl,因此您应该按如下方式编写代码:
if (liveUrl ) {
this.liveUrl = (liveUrl == '') ? null : liveUrl;
}
说明: 当参数 liveUrl 为 null 或未定义时,结果将始终为 false,否则为 true。 由于您希望空字符串也被视为 null,因此我们需要第二个条件。
当 this.liveUrl 具有正确的值时,让我们转到 canPlayLive 变量:
this.canPlayLive = this.liveUrl || false;
说明: 当 this.liveUrl 为 null 时,将被视为 false,因此结果将为 false。
当 this.liveUrl 不为 null 时,它被视为 true,因此 true 或 false 总是给我们 true。
关于javascript - 在构造函数中传递参数时无法设置对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25866417/