更新:我添加了有关如何使用常量来回答问题的更多详细信息。我观察到的实际问题是常量被添加到全局对象中,因此我担心潜在的名称冲突。
我为我的团队定义了一个 WebComponent。该组件使用了几个常量,为了方便起见,我只是在文件顶部定义了这些常量。
const SESSION_KEEP_ALIVE = "session-keep-alive";
const MILLISECONDS_IN_MINUTE = 60000;
const PAGE_TIMEOUT_DIALOG_ID = `${SESSION_KEEP_ALIVE}-extend-session-dialog`;
const YES_BUTTON_ID = `${PAGE_TIMEOUT_DIALOG_ID}-yes-button`;
const NO_BUTTON_ID = `${PAGE_TIMEOUT_DIALOG_ID}-no-button`;
// TEMPLATES
const PAGE_TIMEOUT_DIALOG_TEMPLATE = document.createElement("template");
PAGE_TIMEOUT_DIALOG_TEMPLATE.innerHTML = `
<uef-dialog action-required="" backdrop="" width="500px" id="${PAGE_TIMEOUT_DIALOG_ID}">
<uef-typography slot="uef-dialog-header">Warning</uef-typography>
<uef-typography line-height="1.5" slot="uef-dialog-body">
Your session will expire in 5 minutes. Do you want to extend it?
</uef-typography>
<uef-button-group slot="uef-dialog-footer" alignment="right" direction="rtl">
<uef-button fill="solid" id="${YES_BUTTON_ID}">Yes</uef-button>
<uef-button fill="outline" id="${NO_BUTTON_ID}">No</uef-button>
</uef-button-group>
</uef-dialog>`;
class SessionKeepAlive extends HTMLElement {
connectedCallback() {
document.body.appendChild(PAGE_TIMEOUT_DIALOG_TEMPLATE.content);
this.dialog = document.getElementById(PAGE_TIMEOUT_DIALOG_ID);
let yesButton = this.dialog.querySelector(`#${YES_BUTTON_ID}`);
yesButton.addEventListener("buttonClick", this.yesButtonClickHandler.bind(this));
let noButton = this.dialog.querySelector(`#${NO_BUTTON_ID}`);
noButton.addEventListener("buttonClick", this.noButtonClickHandler.bind(this));
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === "delay") {
if (!isNaN(newValue)) {
this.timeoutDelay = newValue * MILLISECONDS_IN_MINUTE;
}
}
}
yesButtonClickHandler() {
this.dialog.removeAttribute("open");
... // Code to extend session elided
}
noButtonClickHandler() {
this.dialog.removeAttribute("open");
}
}
window.customElements.define(SESSION_KEEP_ALIVE, SessionKeepAlive);
在这个简化的示例中,您可以看到我如何使用两个常量。我用它来注册 WebComponent 并为组件中的元素定义 ID。这个常量似乎确实大于 WebComponent 的范围。
另一个 - MILLISECONDS_IN_MINUTES - 可能可以用文字替换。我确实考虑过将其定义为构造函数中的另一个属性,但我想知道处理这些情况的最佳方法。
我尝试了一些方法 - 包括使用匿名函数来限制范围:
(function() {
// The above code, here
}) ();
这有效,但感觉不对。
我尝试使用“static”关键字将它们定义为类级变量。不幸的是,这不是“static”关键字在 JavaScript 中的工作原理。
我也考虑过使用 Constants 文件,但使用组件的目的是封装代码,而不是将各个方面放在单独的文件中。
有什么建议吗?
现在我决定推荐使用匿名函数闭包:
(function() {
const MY_CLASS_NAME = "my-class";
class MyClass extends HTMLElement {
// Stuff
}
window.customElements.define(MY_CLASS_NAME, MyClass);
}) ()
这是可行的,并且这是 JavaScript 中的常见做法。
如果你想限制范围(不使用模块),你可以只使用一个块,如下所示:
{
const MY_CLASS_NAME = "my-class";
class MyClass extends HTMLElement {}
}