Infinite prototype inheritance in Javascript

I am learning prototypal inheritance in Javascript, and as I understand it, I am trying to use it to send a process to an infinite recursive chain.

My idea of ​​prototype inheritance is that an object (which is a function) contains a prototype of the link. Any instance of this object points to this. Therefore, if I say instance.someproperty, it looks at the prototype chain of the parent object.

Assuming this, if I just point out the list of function prototypes to myself, it should go into an infinite loop when an object tries to access some property.

 var p = function(){};

 p.prototype = p;
 // I also tried p.prototype = new p();

 var q = new p();

 // and now when I say q.something, it should never be able to find it.

I want to know why this does not work and how I can make it go into an endless loop.

+4
2

:

function P(){};
P.prototype = P;

ECMA-262 [[Prototype]].

P.prototype P [[Prototype]], :

P : P[[Prototype]] -> Function.prototype -> Object.prototype -> null

, P P.prototype , [[Prototype]] P:

p : p[[Prototype]] -> P : P[[Prototype]] -> Function.prototype -> Object.prototype -> null

.

P.prototype p :

p : p[[Prototype]] -> P.prototype -> Object.prototype -> null

, __proto__ ( [[Prototype]]) , , , , Firefox :

"TypeError: cyclic __proto__ value".
+5

, :

var p = function(){};

p.prototype = p;
// I also tried p.prototype = new p();

var q = new p();

, , p, p, ( , length, prototype ..). Function.prototype, , , Object.prototype.

- , . new p() p.prototype, prototype , prototype .


. , , .

( ), .

:

var a = { b: 1 };
a.__proto__ = a;

, , , TypeError ( B ES6).

b, .

, ( ​​) , , , , return undefined.

, , :

var a = { x: 1 };
var b = { y: 2 };
b.__proto__ = a;
a.__proto__ = b;

( - ).

+1

Source: https://habr.com/ru/post/1537029/


All Articles