1

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.

1
  • 1
    This is not specific to ES6. This wasn't possible in ES5 either. Commented Jan 11, 2016 at 18:38

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You could also make create a static function on Foo and just do Foo.create(baz) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.