将参数传递给构造函数时,无法设置对象的属性

时间:2014-09-16 10:29:41

标签: javascript javascript-objects

我需要根据创建对象时发送的参数值,设置两个标记canPlayLiveisSubscribedtruefalse

基本上,当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);

2 个答案:

答案 0 :(得分:1)

由于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。

答案 1 :(得分:0)

我能够使用!liveUrl代替''来解决我的问题。

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 || !liveEntryId ? null : liveEntryId;
    this.liveUrl = liveUrl === null || undefined || !liveUrl ? null : liveUrl;
    this.timeLists = timeLists;
    this.canPlayLive = this.liveUrl === null || undefined || !liveUrl ? false : true;
    this.isSubscribed = subscribedFlag == 0 ? false : true;
}