javascript - Prototype inheritance is not working as expected -
since javascript childhood have read , followed should override constructor in case of prototypical inheritance. surprised see following example outputs same @ console if overriding constructor statement commented. please enlighten.
function a() { console.info("a constructor"); } function b() { console.info("b constructor"); } b.prototype = a.prototype; b.prototype.constructor = b; // need statement? console.info("cp 1"); var b = new b(); console.info("cp 2");
before getting constructor part, there problem in code. making both b.prototype , a.prototype same, doing
b.prototype = a.prototype; this means that, cannot identify parent of objects constructed these functions. try this
console.log(new b() instanceof a, new b() instanceof b); // true true this expected, since b created b , b created a's prototype. but
console.log(new a() instanceof a, new a() instanceof b); // true true whaaat? how come object of a instance of b? because, since made b.prototype same a.prototype, when object a tries find out if prototype (a.prototype prototype of object created a) exists anywhere in prototype chain of b. since b.prototype same a.prototype, object of a can treated object of b.
the right way is,
b.prototype = object.create(a.prototype); now, making b's prototype object created prototype of a. so, not a'prototype, object created based on prototype of a.
now, if don't do
b.prototype.constructor = b; try printing constructor property of object created b, without line
console.log((new b()).constructor); // [function: a] since b's prototype still has constructor value copied a's prototype, still refers function a. why replace b function object.
Comments
Post a Comment