What should a JavaScript constructor return if it fails?

前端 未结 4 1904
醉酒成梦
醉酒成梦 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:51

    My first approach:

    1. Don't allow a constructor to fail; consider alternatives

    My second approach:

    1. If a constructor fails, it must only fail because of a programming error and thus;
    2. should throw an exception and;
    3. must not return 'a status code' (see Emmett's answer for why returning null doesn't work anyway)

    I have never designed a constructor (something invoked as the target of new) to return anything except an object of the "expected" type.

    Fail fast, avoid being too clever, and save time debugging hard-to-find bugs.

    Happy coding.

提交回复
热议问题