Athan Clark
Athan Clark

Reputation: 3980

Failing in a Javascript Constructor

I'm currently building an (ES6) javascript constructor, and was wondering how I should handle "failure". I was thinking about plainly logging to the console and setting this = undefined;, but for some reason that's an "illegal left-hand side assignment". This is roughly what I had in mind:

class Foo {
  constructor(foo) {
    if (foo === bar) {
      // considered "success"
      this.foo = foo;
    } else {
      // failure
      console.log("oh noes!");
      this = undefined;
    }
  }
}

Would this be considered a wise practice? I'm just trying to understand what the best practice should be, for failing during the use of a constructor.

Upvotes: 1

Views: 310

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32521

You can't assign directly to this but if you do want to return undefined in the event of an error, you could use a factory method:

class Foo {
  constructor(foo) {
    if (foo !== bar) {
      throw new Error('oh noes!');
    }
  }
}

let Factory = {
  createFoo(f) {
    try {
      return new Foo(f);
    } catch(e) {
      console.log(e.message);
    }
  }
};

let myFoo = Factory.createFoo(baz);

Upvotes: 1

Related Questions