JavaScript
In the books, I read that in order for an object to inherit from a prototype, you need to assign this prototype to the property .constructor.prototype
. In the same books, it is written that the Javascript engine uses this principle to organize a prototype inheritance chain, because each prototype in turn has the similar chain of properties.
But when I try to use it in practice, I get an unexpected result:
function Point2d() {this.x = 0; this.y = 0;};
Point2d.prototype.message = function() {
return 'I am Point2d: (' + this.x + ','+ this.y + ')';
};
let p = new Point2d;
let json = JSON.stringify(p);
let pp = JSON.parse(json);
// I need the parsed object be the Point2d instance,
// therefore I do it:
pp.constructor = Point2d;
p.constructor == pp.constructor; // true
// But I see it:
pp.constructor.prototype == Point2d.prototype; // true
Object.getPrototypeOf(pp) == Point2d.prototype; // false
console.log(p.message()); // it works fine
// Oops... Here I get the error: 'pp.message is not a function'.
console.log(pp.message());
// Ok... I see that each object also has the __proto__ property.
// Change it:
pp.__proto__ = Point2d.prototype;
console.log(pp.message()); // now it works fine too
But in the books I read, nothing is written about the __proto__
property.
Why does the __proto__
point to another prototype? Why this property exists? Why not to use .constructor.prototype
only?