I would like to create an object that extends the function of an HTML element by putting the element in the object's prototype chain.
I though I could do this with something like the following:
var el = document.createElement( "div" );
el.innerHTML = "foo";
var wrapper = Object.create( el );
alert( wrapper.innerHTML );
The above does not work, whereas the following does:
var el = document.createElement( "div" );
el.innerHTML = "foo";
var wrapper = Object.create( el );
alert( wrapper.__proto__.innerHTML );
It seems odd that explicitly looking inside the prototype would be necessary to find a given property.
It does not work because you are using the .innerHTML
getter on an object that is not a native DOM element and does have none of its internal slots.
I would like to create an object that extends the function of an HTML element by putting the element in the object's prototype chain.
That's the wrong way round. To extend the functionality of an element, you need to put your custom function in its prototype chain, so that methods are still called on the element itself. You can use Object.setPrototypeOf
for that, or make your own ES6 subclass
(and possibly register it as a custom element type).
But the best solution would be to simply put a wrapper object around the element. Also have a look at http://perfectionkills.com/whats-wrong-with-extending-the-dom/.