I don't want to inherit or extend from the Error
so don't mark my question is duplicate if the solution you post is inherit or extend from Error
Below is my sample code and run on Chrome. Comments below console.log
is output from Chrome developer tool's console tab.
What I want to know is why the Error
object can output the raw string message but my CustomError
will output a object.
Is it possible to implement an object like the Error
object can output the raw string message
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
<script>
function CustomError() {
this.message = "MyErrorMessage";
}
var nativeError = new Error();
var customError = new CustomError();
console.log(nativeError);
// Error
console.log(customError);
// CustomError {message: "MyErrorMessage"}
Error.prototype.message = "Modify native error prototype message";
var nativeErrorAfterModifyPrototypeMessage = new Error();
console.log(nativeErrorAfterModifyPrototypeMessage);
// Error: Modify native error prototype message
CustomError.prototype.message = "Modify custom error prototype message";
customErrorAfterModifyPrototypeMessage;
var customErrorAfterModifyPrototypeMessage = new CustomError();
console.log(customErrorAfterModifyPrototypeMessage);
// CustomError {message: "MyErrorMessage"}
customErrorAfterModifyPrototypeMessage.__proto__.message =
"Modify custom error prototype message";
console.log(customErrorAfterModifyPrototypeMessage);
//index.html:37 CustomError {message: "MyErrorMessage"}
</script>
</html>