In the following example the constructor function which creates a new node (here named Node
) lies outside the class whose method calls it:
class Collection {
constructor() {
this.collection = [];
};
addNode(value) {
const node = new Node(value);
this.collection.push(node);
console.log(this.collection);
};
};
function Node(value) {
this.value = value;
}
const col = new Collection();
col.addNode("foo");
However, I'd like to have the constructor function inside the class (mainly because it's only used by that class). This will fail (x is not a constructor
):
class Collection {
constructor() {
this.collection = [];
};
Node(value) {
this.value = value;
};
addNode(value) {
const node = new this.Node(value);
this.collection.push(node);
console.log(this.collection);
};
};
const col = new Collection();
col.addNode("foo");
I'm also aware that Javascript currently does not support nested classes. What I'm currently doing is simply declaring the Node
constructor inside the addNode
method.
But I'm curious: is it possible to have such constructor function iside the class that calls it?