简体   繁体   中英

Why DOM has object oriented structure when JS is not?

In DOM (JS rappresentation of HTML parsed file) we have this structure(where < is for " inherited "):

   Object(JS object) < Node < Element < HTMLElment < HTMLBodyElement, HTMLDivElement, etc..
   Object(JS object) < Node < DOcument < HTMLDocument
   ...

All these nodes are called interfaces ( https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement ) in every documentation I have checked.

I don't understand how is this possible in JS (not object-oriented, no interfaces, etc)? I have a background in C++, so maybe I am confusing DOM "object-oriented" structure with a real one. Any clarification?

I don't understand how is this possible in JS (not object-oriented, no interfaces, etc)?

There's no problem modelling the DOM's structure in JavaScript. JavaScript is very object-oriented, including supporting inheritance. JavaScript uses prototypical inheritance . Example:

 // Create an object with a method const base = { baseMethod() { console.log("baseMethod"); } }; // Create an object using `base` as its prototype, // perhaps add a property to it const sub = Object.assign(Object.create(base), { subMethod() { console.log("subMethod"); } }); // Sub inherits `base`'s properties sub.baseMethod(); // "baseMethod" // And has its own sub.subMethod(); // "subMethod"

JavaScript also overlays something on top of prototypical inheritance that seems rather class -like (it isn't, it's still prototypical, but it's more comfortable for people coming from class-based languages). For instance, here's a three-layer inheritance model (rather like Node < Element < HTMLElement ) using class syntax (but again, we could do all of this without class syntax, too):

 class Base { baseMethod() { console.log("baseMethod"); } } class Sub extends Base { subMethod() { console.log("subMethod"); } } class SubSub extends Sub { subSubMethod() { console.log("subSubMethod"); } } const x = new SubSub(); x.baseMethod(); // "baseMethod" x.subMethod(); // "subMethod" x.subSubMethod(); // "subSubMethod" console.log(x instanceof Base); // true console.log(x instanceof Sub); // true console.log(x instanceof SubSub); // true console.log(x instanceof Date); // false (just to show it's not always true ;-) )

(The Object base of that structure is implicit.)

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