Home > Enterprise >  Is it possible to have a constructor function as a method in a class?
Is it possible to have a constructor function as a method in a class?

Time:10-24

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?

CodePudding user response:

Option 1: defining Node as an instance field and setting it to a function (basically your first example)

class Collection {

  constructor() {
    this.collection = [];
  };

  Node = function (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");

Option 2: using a nested class (which is also an instance field)

class Collection {

  constructor() {
    this.collection = [];
  };

  Node = class Node {
    constructor (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");

Option 3: using either of the above, but making it a static field instead (recommended). This is so that the class is not re-created for every instance of Collection you create.

class Collection {

  constructor() {
    this.collection = [];
  };

  static Node = function (value) {
    this.value = value;
  };

  addNode(value) {
    const node = new Collection.Node(value);
    this.collection.push(node);
    console.log(this.collection);
  };
};

const col = new Collection();

col.addNode("foo");

  • Related