What should a JavaScript constructor return if it fails?

前端 未结 4 1902
醉酒成梦
醉酒成梦 2021-02-03 18:33

If I have a javascript class which cannot be instantiated what should the constructor return that I can test for. The constructor always returns an object so I cannot return nul

4条回答
  •  青春惊慌失措
    2021-02-03 18:44

    Use I sentinel. I like to

    return {invalid:true};
    

    This looks clean:

    var x = new X();
    if (x.invalid) { // ...
    

    (There's no way to return a non-true value from a constructor, so you can't put new in the conditional as you might with another language.)

提交回复
热议问题