javascript - 在构造函数中传递参数时无法设置对象的属性

标签 javascript javascript-objects

我需要根据参数值将两个标志 canPlayLiveisSubscribed 设置为 truefalse创建对象时发送。

基本上,当传递 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/

相关文章:

javascript - 返回发行专辑最多的年份的函数

backbone.js - Handlebars 嵌套对象

javascript - 使用配置文件路径打开 firefox [selenium webdriver NodeJS]

javascript - immutable.js & react.js setState 清除对象原型(prototype)

javascript - 如何将一个类添加到一个div,让它等待一段时间,然后再将另一个类添加到另一个div?

javascript - 按值比较数组中的所有对象

Javascript - 没有 float 的双值?

javascript - 输入 {a :1} giving 1, 和 {a :1, b :2} giving an error in a Javascript console? 的行为是什么

javascript - 使用 jquery-csv 库时遇到问题

javascript - asp 按钮和历史返回 onclientclick