How do you define a static constructor within a JS class?
I managed to write something that somehow works but it requires to write a specific codepath in constructor
for when an IngredientsDB
object is instantiated from the static method IngredientsDB.fromXML()
:
class IngredientsDB {
constructor(...args) {
if (arguments.length === 0) {
this.document = null;
} else {
this.document = new DOMParser().parseFromString("<ingredients/>", "text/xml");
// ... process args
}
}
static fromXML = function fromXML(xmlString) {
const db = new this;
db.document = new DOMParser().parseFromString(xmlString, "text/xml");
return db;
}
toString() { // concise output for testing
const ingredientsNode = this.document.firstChild;
let str = ingredientsNode.tagName + ":";
let childNode;
for (childNode of ingredientsNode.children)
str += " " + childNode.tagName;
return str;
}
}
const xml = document.getElementById("ingredients").textContent.trimStart();
console.log(IngredientsDB.fromXML(xml).toString());
<script id="ingredients" type="text/xml">
<ingredients>
<tomato/>
<meat/>
<cheese/>
</ingredients>
</script>