What should a JavaScript constructor return if it fails?

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

    Returning any non-object from the constructor is practically the same as exiting the constructor. (The constructor will return a new object, with a prototype if one was specified.)

    So, returning null, undefined, or 42 from the constructor are equivalent.

    Check out section 13.2.2 of the ECMAScript spec (pdf) for more info.

提交回复
热议问题