简体   繁体   中英

What best practice when instantiating a JavaScript object?

When instantiating an object in JavaScript, (particularly when there are multiple objects being instantiated in the same script block) - is it good practice to wrap the instantiation in a try catch statement so if the object errors it doesn't affect any other objects within the script?

Eg is it best practice for this:

try{
    new navigation();
}catch(e){
  //handle exception for navigation fail
}

try{
    new Accordian();
}catch(e){
  //handle exception for accordion fail
}

as opposed to

new navigation();
new accordian();
and so on.....

I can't see any good reason for doing that. If the likelihood of an error being thrown from a simple object instantiation is high, there should be something very wrong with the code. Besides, try/catch statements are known to be slow in JavaScript.

is it good practice to wrap the instantiation in a try catch statement so if the object errors it doesn't affect any other objects within the script?

No, it is not good practice to wrap the statements that new up an object in a try catch block. You instead should be looking at what kind of errors could possibly be raised when instantiating an object and move the initialization code it's own function where the errors can be handled. The contructor should not try and do too much. Keep it's reason for being simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM