Skip to content

自定义元素与生命周期:练习答案 ​

define、升级与名称约束 ​

自定义元素名称必须包含连字符,重复 customElements.define 会抛出异常。元素先出现在 DOM、后调用 define 时会发生升级;答案应在定义前后分别记录 constructor 与 connectedCallback 的调用。

connected/disconnected 与资源 ​

js
class ClockPanel extends HTMLElement {
  connectedCallback() {
    this.timer = setInterval(() => { this.textContent = new Date().toISOString() }, 1000)
  }
  disconnectedCallback() {
    clearInterval(this.timer)
    this.timer = undefined
  }
}

移动节点可能再次触发 connected,因此生产代码应避免重复创建 timer;移除后文本不再变化,且控制台不应继续出现更新日志。

observedAttributes 与反射 ​

只有列在 static observedAttributes 中的属性变化才触发 attributeChangedCallback。回调参数为 (name, oldValue, newValue);布尔属性应按“存在即 true”处理,不要把字符串 "false" 当成 false。属性反射时避免在回调中无条件再次 setAttribute 造成循环。

章节入口核对 ​

以下入口对应本章概览或综合练习,答案核对沿用本章各知识点的实现与日志。

用心记录每一步成长