简体   繁体   中英

Difference between object and interface in JavaScript

I'm currently learning JavaScript using the Mozilla Developer Network as a reference.

It confuses me that MDN refers to objects as interfaces.

For example: Document.createTreeWalker()

At the bottom, there is a link to the TreeWalker Object, but it says:

The interface of the object it creates: TreeWalker

How can TreeWalker be an interface if I can instantiate it? And TreeWalker is only an example, almost every object in MDN is referred to as an interface.

I come from a Java background, so the use of interface in this context is not clear to me. Does interface in JavaScript mean something different than in Java?

"interface" arises in this context because that is the term used in standards applicable to the (javascript) object being described on MDN.

Web standards use an interface definition language or IDL described in Web IDL to describe the behavior of browser objects independent of the language, eg javascript, used to manipulate them. Hence TreeWalker is documented as an "interface" in the Document Object Model (DOM) Level 2 Traversal and Range Specification

So in a sense MDN is simply using the vocabulary of the standard which defines the interface exposed by the browser object it is describing. To what extent the subject of the documentation would be described as an "interface" in another language might vary on a case by case basis.


CF the definition of interface used in web standards.

No, javascript doesn't really have a true interface type or anything. The createTreeWalker() function simply uses Object.create to return on object.

See also:

How to implement interface in javascript

Does JavaScript have the interface type (such as Java's 'interface')?

There isn't a true interface built into JavaScript. It seems like they are referring to an object that gets inherited from as the interface. In your example Document.createTreeWalker() returns an instance of the TreeWalker object.

// myTreeWalker is your object. TreeWalker is the interface.
var myTreeWalker = Document.createTreeWalker()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM