Echo JS 0.11.0

<~>

tracker1 70 days ago. link 2 points
Sigh... the article doesn't even cover what it says in the title.

First, if you use the class syntax, then you will get an error if you don't use new.

    class Foo {
      // implementation details go here
    }

    Foo(); // Error: Class constructor Foo cannot be invoked without 'new'

Second, you can do the same kind of behavior in a constructor function.

    function Foo() {
      if (!(this instanceof Foo)) {
        throw new Error("Class constructor Foo cannot be invoked without 'new'");
      }
      // implementation details go here
    }

The article does discuss the issue, but gives no real resolution, such as above.

The article's solution break the type for the returned object... you may as well not use a constructor/class at all if that's your approach, which is fine, but don't use a constructor function naming `Foo` if you're returning a custom object, use `createFoo` or another appropriate name.

Alternatively...

    function Foo(...args) {
      if (!(this instanceof Foo)) {
        return new Foo(...args);
      }
      ...
    }
softxml 69 days ago. link 1 point
Hi Michael

You are absolutely right for pointing out this important issue about losing prototype chain! I wrote about this problem at the very end of the article and now added optimal solution by using method of Constructors calling themselves.

Thanks!
tracker1 69 days ago. link 1 point
Would still probably lean into the spread for the nested call... since everything except for IE11 supports it now.

https://caniuse.com/#feat=mdn-javascript_operators_spread_spread_in_function_calls

Same goes for classes actually.