darKnight
darKnight

Reputation: 6481

Understanding JavaScript and DOM 'Interfaces'

I am playing around with vanilla JavaScript and the DOM. While glancing through MDN, I came across the term Interface. As per MDN, there are various basic Interface from which other DOM elements inherit. These are HTMLElement, Element, Node and EventTarget. I understand the concept of a Class in JavaScript, but what does an Interface mean in JavaScript? I tried playing around with the HTMLElement interface, but got errors.

const myElem1 = new HTMLElement('div')
const myElem2 = new HTMLElement('')

Both statements above throw the error Uncaught TypeError: Illegal constructor. Also, an Interface does not seem to be a Class. Consider this code:

const elmnt = document.getElementById("myDIV");
const height = elmnt.clientHeight

clientHeight is a property on the Interface Element, as per MDN. So if Element was a class, clientHeight should have been on Element.prototype.clientHeight, and not on Element.clientHeight.

Is it possible to use these Interfaces in our JavaScript program? If so, what's the correct way, and what are some use cases?

Upvotes: 3

Views: 526

Answers (1)

Quentin
Quentin

Reputation: 943568

Interface is a general term in OO-programming.

It is like a class in that it defines features that must appear on an object, but you can't use it directly. Instead you must use a class which implements it.

So you can't create an instance of HTMLElement, but since Div implements HTMLElement and Span implements HTMLElement you can create an instance of Div or Span and either will satisfy a requirement to have an HTMLElement.

Interfaces are generally used to avoid problems in multiple inheritance. A class can implement multiple interfaces which have overlapping requirements (say both interfaces require a Dance method) whereas if it extended two classes which had a Dance method you'd need to pick which of the two parent classes to take Dance from an which to ignore).


Note that JavaScript has no Interface language feature (although TypeScript does). The term is just used in the DOM documentation as it is written in general OO terms and not JavaScript specific terms.

Upvotes: 5

Related Questions