0

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?

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • Please read tags descriptions before using them. This question clearly isn't about the Prototype framework. – Michał Perłakowski Jun 09 '17 at 11:51
  • I deleted that tag. Thank you. – Andrey Bushman Jun 09 '17 at 11:54
  • No, I removed the [prototypejs] tag, and you removed the [prototype] tag, which is valid. – Michał Perłakowski Jun 09 '17 at 11:56
  • 1
    "*nothing is written about the `__proto__` property.*" - and that's a good thing! You should not use it. Look at `Object.getPrototypeOf` and `Object.setPrototypeOf`. – Bergi Jun 09 '17 at 13:31
  • "*you need to assign this prototype to the property `.constructor.prototype`*" - no, I'm pretty sure that's not what they've written. What is assigned to *a* constructor's `.prototype` property will be used for the prototype chain of any *new instances constructed from that function by using `new`*. Just setting `.prototype` doesn't change anything, and the `.constructor` property on prototype objects has even less to do with it. – Bergi Jun 09 '17 at 13:34
  • The solution you're looking for is `Object.setPrototypeOf(pp, Point2d.prototype)` – Bergi Jun 09 '17 at 13:35

0 Answers0