es6 类 - 将布尔值传递给构造函数

dav*_*djh 2 javascript constructor boolean class ecmascript-6

我试图掌握 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
});
Run Code Online (Sandbox Code Playgroud)

autoDisplayis always true,无论我创建类的实例时传递给它什么,它都采用默认值。

如果我改成autoDisplay一个字符串它工作正常。

你不能像这样将布尔值传递给构造函数吗?

T.J*_*der 5

false || true总是true||是这样评估的:

  • 评估左侧
  • 如果左侧为,那就是结果
  • 否则,评估右手边并使 reslt

所以||不是这样做的方法。如果您希望能够提供任何其他虚假值,例如, , 等0,您也会遇到麻烦。""null

可以使用typeof options.autoDisplay === "undefined""autoDisplay" in options(更多在此问题及其答案中)

this.autoDisplay = typeof options.autoDisplay === "undefined" ? true : options.autoDisplay;
Run Code Online (Sandbox Code Playgroud)

...但是您使用的是 ES2015(“ES6”),因此您可以通过使用默认参数参数解构来避免所有这些样板:

constructor({message = 'default cookie message', autoDisplay = true} = {}) {
    this.message = message;
    this.autoDisplay = autoDisplay;
    console.log(this.message, "|", this.autoDisplay);
}
Run Code Online (Sandbox Code Playgroud)

现场示例:

this.autoDisplay = typeof options.autoDisplay === "undefined" ? true : options.autoDisplay;
Run Code Online (Sandbox Code Playgroud)

注意在我们的函数代码中,我们甚至没有options了;当函数被调用时,参数从我们的选项对象中解构出来。

让我们看看那个声明:

{message = 'default cookie message', autoDisplay = true} = {}
Run Code Online (Sandbox Code Playgroud)

{message = 'default cookie message', autoDisplay = true}部分说:

  • 第一个(仅在我们的例子中)参数将是我们想要解构的对象(感谢{}它周围的)
  • 如果上面没有message属性,则默认为“默认 cookie 消息”
  • 如果没有 'autoDisplay' 属性,则默认为 true

...并且该= {}部分说:如果未给出参数,则默认为空白对象(之后上述两个默认值将生效)。


旁注:JavaScript 中压倒性的约定是构造函数(类)用大写的第一个字母(通常是 CappedCamelCase)编写,SiteAlert而不是site_alert. 您不必遵循惯例,但如果您不知道,只需将其标记即可。