I just learned about self-referencing objects in this question. This is awesome that people here at StackOverflow know every dark corner of JavaScript.
Today I wanted to use my knowledge and use a self-referencing object in my code but I couldn’t make it.
I’m trying to make a self referencing object that have different values in different levels. I want every level of my object have the main properties that I’m defining in level one and level two and below have all properties of level two and so on…
Let’s see what I’m trying to do:
obj is an object that is self referencing, it means obj.obj refer to obj and so on…
I want to have a property in obj.obj but not in obj, like obj.obj.newProp = "myString" and then every level below the level two should have the newProp.
This is the code I wrote that I’m sure is not current!
var obj = {},
obj.obj = obj,
obj.obj.newProp = "myString";
But when I look at obj it contains "myString". How can I prevent obj refering to obj.obj?
But they’re the same object. You can’t have and not have a specific property on the same object at the same time.
EDIT:
If you’re talking about inheritance, then you need to set one object as the prototype object of another. There are a couple of different approaches.
If you’re only supporting modern JavaScript environments, you can use
Object.create().If you’re supporting older browsers, then you can use a constructor function, and set the
prototypeobject of the constructor toobj1, and all objects created from the constructor will haveobj1in its prototype chain.