有人可以向我解释这个JavaScript代码吗?

时间:2010-12-28 20:43:28

标签: javascript try-catch

// Create an object type UserException  
function UserException (message){  
  this.message=message;  
  this.name="UserException";  
}  

// Make the exception convert to a pretty string when used as  
// a string (e.g. by the error console)  
UserException.prototype.toString = function (){  
  return this.name + ': "' + this.message + '"';  
}  

// Create an instance of the object type and throw it  
throw new UserException("Value too high");

如何使用?

1 个答案:

答案 0 :(得分:2)

这是您在javascript中创建对象的方法,在本例中是UserException具有toString功能的对象。它可能会这样使用:

try {
    throw new UserException("something went wrong");
} catch(ex) {
    console.log(ex);
}