JavaScript interfaces in MDN

Viewed 4012

As far as I know JavaScript, being OOP based on prototypes - and not classes - do not contemplates interfaces, but relies instead on ducktyping.

I can often see however in MDN online documentation some objects described as "interfaces", such as Storage in here:

https://developer.mozilla.org/en-US/docs/Web/API/Storage

Indeed window.Storage exists and is a function, but is not a constructor or a factory and fails if invoked. It has no members like the ones described in that page, as window.localStorage instead has. The page

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

points window.Storage as the object accessed by window.localStorage. I understand that window.localStorage is a native object, but I would like to understand the role of window.Storage and why it is addressed by MDN as an "interface", in what sense: is it a specification to which browser developers adhere, rather than a strict "interface" as intended in class-based paradigm?

Thank you in advance, sorry for the strange question. Just trying to deepen my comprehension of ES.

1 Answers

It's not a class with a constructor that you can instantiate, so we don't call it a class. It's not a prototype object either.

MDN uses the term interface in the generic OOP meaning, which is not restricted to class-based inheritance but refers to a type definition with method signatures.

However, it also uses the term interface in the very specific context of the Web Interface definition language, which the web storage specification uses to define Storage as an interface indeed. These WebAPIs can be implemented in multiple languages (called "bindings"), though JS is most common. The WebIDL spec even defines how such an interface is to be represented in JavaScript (the "ECMAScript binding"), in particular that the linear inheritance of interfaces is implemented using prototype inheritance between interface objects and their .prototypes (basically as if using class Storage extends …). This means localStorage instanceof Storage and Storage.prototype.hasOwnProperty('getItem') work as expected.

Related