Maybe it's stupid, but I'm a beginner, and I wanted to use OOP tools.

More precisely, I wanted to add additional behavior to the node by creating a descendant class of the original node, defining some properties and expanding it with new methods and adding it to the document.

But nothing works. Is such a move possible, in general?

function MyNode(){ this.className = "my_node" } MyNode.prototype = document.createElement("div"); MyNode.prototype.myMethod = function(){ // some }; document.body.appendChild(new MyNode()); 

What did I want to do? There is a class of nodes, with general behavior and parameters. Create them in the following way:

 var node = document.createElement("div"); node.className = "my_node"; node.добавляетТекст = function(текст){ this.innerHTML = текст; }; node.добавляетТекст("Я твоя совесть"); document.body.appendChild(node); 

That is, if you follow the principles of OOP, I would have to allocate such nodes into a general class. That is, this is not a new type of tags (although I’m unsure, I suspect that there may be compatibility problems, although it would probably be more correct), but simply defining a new behavior only for created objects, js allows it.

  • add a minimal example of what you were trying to do. Maybe you need Web Components - Grundy
  • Added, thanks. - Mr Fix
  • In the future it will be possible, but now the browser support for such tricks is pretty bad - andreymal
  • In general, no one bothers to inherit. Simply creating the necessary element will not work, at least for now, because there are no types of html elements, there are only interfaces, and they cannot be created by calling the constructor. - Grundy
  • And another big question is whether inheritance is needed here, or is it better to simply store a reference to the desired element in the field - Grundy

0