【发布时间】:2023-03-10 06:05:01
【问题描述】:
我正在尝试掌握 es6 类,但我似乎无法将布尔值传递给构造函数。
在下面的代码中
export default class site_alert {
constructor(options) {
this.message = options.message || 'default cookie message';
this.autoDisplay = options.autoDisplay || true;
console.log(this.autoDisplay);
}
}
var sitemessage = new site_alert({
message:"Some string",
autoDisplay: false
});
autoDisplay 始终是true,无论我创建类的实例时传递给它的什么,它都采用默认值。
如果我将autoDisplay 更改为字符串,它可以正常工作。
你不能像这样将布尔值传递给构造函数吗?
【问题讨论】:
-
那是因为
||是一个或比较器。您实际上说的是options.autoDisplay OR true,无论options.autoDisplay的值如何,它总是解析为true。 -
即使您将值作为 false 传递,它也会在构造函数中结束为: this.autoDisplay = false ||真的,这确实是真的。
标签: javascript class constructor boolean ecmascript-6