Easy Workaround: Working Script
function ErrorChild(name, message) { // Error.call(this); this is not needed this.name = name; this.message = message; } ErrorChild.prototype = Object.create(Error.prototype); ErrorChild.prototype.constructor = ErrorChild; var myerror = new ErrorChild("test", "Help!"); document.body.innerHTML += myerror.message;
The above does not violate the expected behavior. When you throw myerror , the correct name and message will be displayed.
Problem
From the ECMA5 language specification:
15.11.1 Error constructor called as a function
When an Error is called as a function, and not as a constructor, it creates and initializes a new Error object. Thus, the call to the Error (...) function is equivalent to the expression for creating the new Error (...) object with the same arguments.
Problem: Error.call(this) , is the equivalent of new Error . But when creating a new Error , the name or message value will not be set. new Error will initialize message with "" by default.
11.15.4.3 Error.prototype.message # Ⓣ Ⓡ The original value of Error.prototype.message is an empty string.
Test
If inside your ErrorChild you should add:
var test = Error.call(this, message); console.dir(test); console.log(test instanceof Error);
test reflects the ECMA5 specification. An instance of Error with the correct message .
Output:
Because Error.call(arguments); automatically translated into new Error(arguments); , scope is lost, so properties are never initialized in the this object.
When Object.create(Error.prototype) , the message property accepts the default value, an empty string.