throw Error('msg') vs throw new Error('msg')

后端 未结 2 1689
庸人自扰
庸人自扰 2020-11-28 04:56
var err1 = Error(\'message\');
var err2 = new Error(\'message\');

What\'s the difference? Looking at them in the chrome console, they look identica

2条回答
  •  感动是毒
    2020-11-28 05:19

    Error does act like a factory, like some other native constructors: Array, Object, etc. all check something like if (!(this instanceof Array)) { return new Array(arguments); }. (But note that String(x) and new String(x) are very different, and likewise for Number and Boolean.)

    That said, in case of an error, it's not even required to throw an Error object... throw 'Bad things happened'; will work, too
    You can even throw an object literal for debugging:

    throw {message:"You've been a naughty boy",
           context: this,
           args: arguments,
           more:'More custom info here'};
    

提交回复
热议问题