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 ) );
}
);
}
}
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:
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.
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 { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With