From f9ffbe305cfe687e245b341ba0adbc1c33521d9b Mon Sep 17 00:00:00 2001 From: Zach Zhao Date: Sat, 16 Feb 2019 23:28:39 -0500 Subject: [PATCH] Prototype Chain Cycles (#25980) * Prototype Chain Cycles * Fix error message --- guide/english/javascript/prototypes/index.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/guide/english/javascript/prototypes/index.md b/guide/english/javascript/prototypes/index.md index 1a1ce873ee..9fb9c6798d 100644 --- a/guide/english/javascript/prototypes/index.md +++ b/guide/english/javascript/prototypes/index.md @@ -61,6 +61,24 @@ console.log(obj2.c); // undefined In above snippet, the statement `var obj2 = Object.create(obj1)` will create `obj2` object with prototype `obj1` object. In other words, `obj1` becomes the prototype of `obj2` instead of `Object.prototype` by default. As you can see, `b` is not a property of `obj2`, you can still access it via the prototype chain. For `c` property, however, you get `undefined` value because it can't be found in `obj1` and `Object.prototype`. +#### Limitations + +While setting the prototypes of objects, ensure that the prototype chain does not form a cycle. + +``` +let apple = {}; +let pear = {}; +let carrot = {}; + + +Object.setPrototypeOf(apple, pear) +Object.setPrototypeOf(pear, carrot) +Object.setPrototypeOf(carrot, apple) // ERROR! +``` +This wil cause the javascript engine to throw a `TypeError: Cyclic __proto__ value` error. + +The reasoning behind this is that the engine does not know which object is more "senior" when passing through the chain. + ### Classes In ES2016, we now get to use the `Class` keyword as well as the methods mentioned above to manipulate `prototype`. The JavaScript `Class` appeals to developers from OOP backgrounds, but it's essentially doing the same thing as above.