【问题标题】:Do I inherit from Element when I extend the HTMLElement interface?扩展 HTMLElement 接口时是否从 Element 继承?
【发布时间】:2023-01-28 21:03:57
【问题描述】:

JS 借鉴了其他语言的类、接口和对象的模型,但有自己的做事风格。

Mozilla documentation正在调用HTMLElement接口。 in继承自Element,依次是一个类。这在 Java 中行不通。

class ContentCardExample extends HTMLElement {

我找到 this example 的 javascript,它确实扩展了接口。在 Java 中,将实现一个接口。这给我带来了很多问题。

1.) 当我扩展 HTMLElement 时,我是否继承了 Element 的方法,或者它们丢失了?

2.) 如果是这样,HTMLElement 是一个类,接口的措辞只是不准确吗?

3.) HTMLElement 是否添加了可以使用的新方法,或者它是否强制我实现 Java 接口意义上的方法?

这个问题与this other question有关,它用原型、思想来表达问题。至少在语法上这不是同一个问题。

【问题讨论】:

  • 文档意义上的“接口”基本上就是 Java 中的 abstract class。它定义了方法并继承了东西,你只是不会得到它的一个实例。
  • 接口只是告诉我,我不能创建类的实例?
  • 本质上-是的。请注意,仅此而已在这种情况下就像在 DOM API 规范中一样。在您使用 TypeScript 之前,其他地方并没有真正的“接口”。那里的界面更像 Java。

标签: javascript class inheritance interface


【解决方案1】:

1.) 当我扩展 HTMLElement 时,我是从 Element 继承方法还是它们丢失了?

您的新子类通过原型链继承了它们。

2.) 如果是这样,HTMLElement 是一个类,接口的措辞只是不准确吗?

这不是不准确的,它是一个文档/规范概念。您在运行时拥有的是主机环境(在本例中为浏览器的 DOM 实现)提供的该接口的具体实现。

3.) HTMLElement 是否添加了可以使用的新方法,或者它是否强制我实现 Java 接口意义上的方法?

这些方法也是通过原型链提供的。比如clickHTMLElement添加的方法(在Element上不存在)。可以看到一个子类继承了它:

// `click` isn't part of `Element`
console.log("click" in Element.prototype);      // false

// It's provided by `HTMLElement`
console.log("click" in HTMLElement.prototype);  // true

// If we define our own element type extending `HTMLElement`...
class MyElement extends HTMLElement {
}
customElements.define("my-element", MyElement);
// ...and create an instance of it...
const x = document.createElement("my-element");
// ...our custom element instance inherits from `HTMLElement`:
console.log(x instanceof HTMLElement);          // true
// ...and via that from `Element`:
console.log(x instanceof MyElement);            // true
// ...and so it has `click`:
console.log(typeof x.click);                    // "function"

【讨论】:

  • 非常感谢你。 Let's phrase Java 有一个非常特殊的术语接口概念。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 2010-09-29
  • 1970-01-01
  • 2013-09-26
  • 2014-09-07
  • 2019-06-07
  • 1970-01-01
相关资源
最近更新 更多