Is there a way to extend SVGElement like HTMLElement

Viewed 566

I'm making a small JS library. I was creating custom elements using the HTMLElement interface. Now I want to make a custom graphing tool and for that, I want my element to extend SVGElement.

I have a class Graph.js which extends SVGElement and a main.js which instantiates a graph.

This is my class Graph.js :


export class Graph extends SVGElement {

    constructor() {
        super();

    }

}

and Main.js:

import { Graph } from './Experimental/Graph/Graph.js';

customElements.define('pro-graph', Graph);

let graph = new Graph();


But for some reason I get this error:

Uncaught TypeError: Illegal constructor.
    <anonymous> debugger eval code:1
1 Answers

The problem is that the line super(); in your constructor is equivalent to new SVGElement(), which throws that exact exception when you call it directly. It also doesn't make much sense to try this, because there are no "pure" SVGElements. SVGElement is an abstract base-class for more specialized elements like SVGCircleElement, SVGPathElement and all the others. But those can't be created through a constructor either. The usual way to create an SVG element is through the factory method document.createElementNS like described here.

When you can not instantiate a class through a constructor, then you can not create a class extending it.

A better approach to your library design might be:

  • Create a wrapper class which doesn't extend SVGElement but instead has an SVGElement in a private variable
  • Create an SVGElement and then attach a couple additional methods to it
Related