0

Edit: I'm closing this question as a duplicate of this.

I can't wrap my mind around this simple concept. I want to create a class, say:

function InputExt() {
    ...
}

And then I want to do something like this:

InputExt.prototype = document.createElement('input');

But this would only give my InputExt methods and properties of a Node, while InputExt instances will not behave as a Node, nor as a HTMLInputElement.

How can I achieve the behavior below?

InputExt.prototype.info = function() {
    console.log(this);
}
var element = document.body.appendChild(new InputExt());
element.info();
Community
  • 1
  • 1
Algoinde
  • 7
  • 5
  • You need to extend the domObject I think http://stackoverflow.com/questions/12689768/how-can-i-extend-the-document-object – xhallix Feb 24 '16 at 10:21

2 Answers2

1
 function InputExt() {
     var element = document.createElement('input');
     for (prop in InputExt.prototype) {
         element[prop] = InputExt.prototype[prop];
     }
     return element;
 }


 InputExt.prototype.info = function() {
     console.log(this);
 }


 var element = document.body.appendChild(new InputExt());
 element.info();
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
  • You rock. This is so simple! Extending the idea: in the `InputExt` definition something like `var self = document.createElement('input'); self.field = 'test'; return self;` can be used to emulate `this` like you would use it in regular class definitions. – Algoinde Feb 24 '16 at 10:50
  • Okay, there's one problem though. Every instance of `HTMLInputElement` now has an `.info()` method. – Algoinde Feb 24 '16 at 10:53
0

If I got you right, I think you need to extend a DOMElement, because that is was document.body.appendChild is creating.

More details How can I extend the document object?

Here is an example of how this could look like

function InputExt(){}

InputExt.prototype.inputnode= document.createElement('input')

InputExt.prototype.info = function(domInfo) {
  console.log(this.inputnode[domInfo])
}

// access your own object
var mynode = new InputExt();
mynode.info("attributes")

// access document prototype
HTMLInputElement.prototype.logme = function(){
   console.log('me')
}

var element = document.body.appendChild(mynode.inputnode);
element.logme()
Community
  • 1
  • 1
xhallix
  • 2,919
  • 5
  • 37
  • 55
  • Yeah, I thought about that. I wanted it to be uniform - the instance of my class being a full-blown `HTMLElement`. Do I just have to make a custom constructor function which returns created `HTMLElement` injected with methods and fields, ditching `prototype` and `new`? – Algoinde Feb 24 '16 at 10:38