Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate an anonymous es6 class within itself

Say I was parsing a tree where a Node could instantiate another Node as a child. This is pretty easy when the class is named:

class Node {
    parseLeaves( leaves ) {
        _.each( 
            leaves,
            ( leaf ) => {
                this.leaves.push( new Node( leaf ) );
            }
        );
    }
}

But what if the class was exported without being named first? How could the class be determined? i.e.

export default class {
    parseLeaves( leaves ) {
        _.each( 
            leaves,
            ( leaf ) => {
                this.leaves.push( new ???( leaf ) ); 
            }
        );
    }
}
like image 735
stakolee Avatar asked Dec 07 '22 22:12

stakolee


1 Answers

It's possible to do what you ask, but I do not recommend it.

All objects in javascript have a constructor property, that points to their class. By "objects", I mean this is true of everything except null and undefined.

export default class {
  createAnotherInstance() {
    return new this.constructor()
  }
}

This is not a good idea, for at least two important reasons:

  1. Unnamed classes make debugging harder. Stack traces that go through the class will lack a helpful name. People inspecting your objects will not know what they're dealing with. If all your classes follow this pattern, a variable that holds an unexpected type will be very hard to detect.

  2. Subclasses that invoke createAnotherInstance will return subclass instances (their own constructor), when you may have wanted the base class. Even if you desire this, the approach makes it look like an accident. In three days time you'll forget, and it may come back to bite you.

I would name the class, if I were you. Names are good. Unnamed things are ambiguous, and only to be used in contexts where there is no other possible interpretation, for either the computer or the programmer.

export default class Node { ... }
like image 53
slezica Avatar answered Dec 10 '22 12:12

slezica