There is an Element function and Element.prototype.draw , used to create the form and input in this form. Completely confused in the assignment. those. The InputElement constructor inherits the Element and adds its type field to inputs, but, unfortunately, I don’t understand how I can correctly set the Element.prototype.draw line with an InputElement that would add this type .

 function Element (name, template, type) { this.name = name; this.classes = ["formClass"]; this.template = template; }; // debugger; function InputElement (name, template, type) { Element.call(this); this.type = type; }; Element.prototype.draw = function (parentElement) { $Element = $(this.template); $Element.attr("name", this.name); $Element.addClass(this.classes.join("")); $Element.attr("type",) $(parentElement).prepend($Element); return $Element; }; var testForm = new Element("form", "<form></form>"); var testInput = new Element("input", "<input></input>", "password"); testForm.draw("body"); testInput.draw("form"); 
  • see an example of inheritance in javascript - here - Stack

1 answer 1

Something like this:

 function Element (name, template, type) { this.name = name; this.type = type; // <-- добавлена строка this.classes = ["formClass"]; this.template = template; }; // debugger; function InputElement (name, template, type) { Element.call(this); this.type = type; }; Element.prototype.draw = function (parentElement) { $Element = $(this.template); $Element.attr("name", this.name); $Element.addClass(this.classes.join("")); if( this.type) $Element.attr("type", this.type); // <-- исправлена строка $(parentElement).prepend($Element); return $Element; }; var testForm = new Element("form", "<form></form>"); var testInput = new Element("input", "<input></input>", "password"); testForm.draw("body"); testInput.draw("form"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Improvement

jQuery allows you to create an HTML element with the transfer of an object of its attributes in this signature: jQuery( element, attributes) . Since there is no fundamental difference between the attributes name , type and, for example, id , class and others that you may want to pass on in the near future, maybe you should pass a property object to your functions? Like that:

 function Element (template, attributes) { if(typeof attributes === "object") { for( var prop in attributes) { this[prop] = attributes[prop]; } } this.template = template || "<div/>"; // по умолчанию div }; // создавать элементв в prototype.draw: $Element = $(this.template, this.attributes); // и вызывать: var testForm = new Element("<form/>", {name: "form"}); var testInput = new Element("<input/>", {name:"form", type:"password"}); 
  • Thank you for your help. Is it possible to do through input.Element? Through the Element is simpler, but how can this be done from the constructor that inherits the Element? - Medvedev A.