Based on your comments I assume you mean ES6 syntax, and are allowing ES6-defined functions that Custom Elements-supporting browsers also support.
To simulate the default ES6 constructor that calls super()
, we can use Reflect.construct
to invoke the HTMLElement
constructor but using the prototype from our HelloElement
consutrctor.
For inheritance, you need to set the .prototype
of the HelloElement
constructor to an instance of HTMLElement
and define methods and properties on that. It's conventional to use use Object.create()
to create a non-functional dummy instance without invoking the constructor here.
You can use Object.defineProperty
to define your static getter for observedAttributes
, but it will usually just be a static list and you can simply set HelloElement.observedAttributes
to an array of attribute names instead.
function HelloElement() {
return Reflect.construct(HTMLElement, [], HelloElement);
}
HelloElement.prototype = Object.create(HTMLElement.prototype);
// Monitor the 'name' attribute for changes.
Object.defineProperty(HelloElement, 'observedAttributes', {
get: function() { return ['name']; }
});
// or just use HelloElement.observedAttributes = ['name']
// if it doesn't need to be dynamic
// Respond to attribute changes.
HelloElement.prototype.attributeChangedCallback = function(attr, oldValue, newValue) {
if (attr == 'name') {
this.textContent = `Hello, ${newValue}`;
}
}
customElements.define('hello-element', HelloElement);
setTimeout(function() {
document.getElementById('example').setAttribute('name', "World");
}, 1000);
<hello-element id="example"></hello-element>
class
es (defined with ES6 syntax) with ES5 syntax, or do you want to know how the prototype inheritance was done with ES5?I could probably use Babel
- this