What should a JavaScript constructor return if it fails?

前端 未结 4 1920
醉酒成梦
醉酒成梦 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 19:04

    It is probably best to throw an exception to notify the caller that the initialization failed and to take appropriate action.

    Return codes are fine, but for the most part there is no motivation for the caller to implement the checks on the return code.

    My advice is to break hard and break soon. This will make contract violations very evident during testing.

提交回复
热议问题