What's the difference between throw Error('msg') vs throw new Error('msg') ?
What's the difference between throw Error('msg') vs throw new Error('msg') ?
In JavaScript, both throw Error('msg')
and throw new Error('msg')
are used to generate and throw errors, but there are subtle differences in how they operate and their implications.
Factory Function vs Constructor:
Error('msg')
acts like a factory function. This means it returns a new error object each time it is called, regardless of whether you use the new
keyword with it or not[1].new Error('msg')
explicitly uses the Error
constructor to create a new error object. Using new
ensures that the error object is an instance of Error
[1].Implications of using new
:
new Error('msg')
, it is clear that you are creating a new instance of an error, which is the typical and recommended way to handle errors in JavaScript. This usage ensures that the prototype chain is correctly set up, and the error instance inherits all methods from Error.prototype
[1][3].Error('msg')
without new
might lead to confusion or errors in a program if the code checks for specific instances of errors using instanceof
. Although in most modern JavaScript environments, Error('msg')
and new Error('msg')
behave similarly, explicitly using...junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào