javascript - Inheritance from native objects -
i seem miss constructor chain inheritance in javascript, native objects. example :
function errorchild(message) { error.call(this, message); } errorchild.prototype = object.create(error.prototype); var myerror = new errorchild("help!"); why myerror.message defined "" after statements ? expect error constructor define "help!" (and override default value of error.prototype.message), if doing :
var myerror = new error("help!") thanks lot !
the simple work-around: working fiddle
function errorchild(name, message) { // error.call(this); 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 doesn't break expected behaviour. when throw myerror, correct name , message display.
the problem
from ecma5 language specification:
15.11.1 error constructor called function
when error called function rather constructor, creates , initialises new error object. function call error(...) equivalent object creation expression new error(...) same arguments.
the problem: error.call(this), equivalent of new error. new error instantiation not set name or message. new error initialise message "" default.
15.11.4.3 error.prototype.message # Ⓣ Ⓡ initial value of error.prototype.message empty string.
test(proof)
if inside errorchild add:
var test = error.call(this, message); console.dir(test); console.log(test instanceof error); // true; console.log(test.message); // "help!"; the test reflects ecma5 spec. error instance proper message set.
conclusion:
because error.call(arguments); gets automatically translated new error(arguments); scope lost, properties never initialised on this object.
when object.create(error.prototype) used, message property takes default value, empty string.
Comments
Post a Comment