Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-invoking class instantiation with es6 classes

I am trying to use Simple “Class” Instantiation where a class can return a new version of itself and return an instantiated version of itself.

function User(first, last){
  if ( this instanceof User ) {
    this.name = first + " " + last;
  } else
    return new User(first, last);
}

I'm trying to see if this is possible with es6 classes.

class User {
  constructor(first, last){
    if ( this instanceof User ) {
      this.name = first + " " + last;
    } else
      return new User(first, last);
    }
  }  
}

However I'm running into this error:

TypeError: Class constructor User cannot be invoked without 'new'

I'm wondering if there's a way around it.

like image 739
ThomasReggi Avatar asked Oct 20 '25 21:10

ThomasReggi


1 Answers

I'm wondering if there's a way around it.

Well, no. And I think that is a good thing. The advantage of using ES6 Class over the previous method is that it actually behaves like a class, without the quirks and confusion. If you take the reasons to do what you are trying to do, from the article you referenced:

First is an issue that new JavaScript programmers will encounter. On a quick observation of the above code it isn’t immediately obvious that the function is actually something that is meant to be instantiated...

Secondly, if a Class-style function is meant to be instantiated, and isn’t, it can in turn end up polluting the current scope...

And those are some of the issues ES6 aims to resolve. So, now, new programmer comes in, try to invoke a class the wrong way, and boom: TypeError. No polluted scope, no unexpected behavior.

like image 156
Hugo Silva Avatar answered Oct 23 '25 11:10

Hugo Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!