There is a code for this plan:

var objParent = { text: 'Нужное значение', objChild: { context: this, context1: objParent, text: 'Ненужное значение', needHere: function(){ console.log(this.text); console.log(this.context.text); console.log(this.context1.text); // Ниодин из вариантов не дает нужного значения }, }, } objParent.objChild.needHere() 

It is necessary to get the value from the parent object, being in the child object. How can I do that?

  • You can do this: console.log(objParent.objChild.text); - Dmitry Polyanin

2 answers 2

You can use the constructor function to create an object.

 function CreateObject() { var objParent = { text: 'текст', objChild: { needHere: function() { console.log(this.context.text); } } }; /* присваиваем, определяем контекст в необходимое место */ objParent.objChild.context = objParent; return objParent; } var objParent = CreateObject(); objParent.objChild.needHere(); 

  • if you remove the function, nothing will change - Grundy
  • @Grundy yes, but it can be used many times, for this it was made - Dmitry Polyanin
  • @Grundy would like to have one function or one expression responsible for the construction of the object; Forget the second, from this point of view did. - Dmitry Polyanin
  • @Grundy, that is, if there can be several points for creating an object in an application, then the principle of DRY works, and not only it. If an object is created only in one place, then I can think without a function. - Dmitry Polyanin

The only way in an object literal to access it with this is to use a function, or a more convenient entry is getter. (more about the definition of this in the question Lost call context )

At the same time, access will be only to the object itself, but not to the parent (in fact, this means a container).

To access the parent, you must specify a link to it directly

 var objParent = { text: 'Нужное значение', objChild: { get context() { return this; // вернет objChild }, get context1() { return objParent; // вернет значение переменной objParent на момент вызова }, text: 'Ненужное значение', needHere: function() { console.log(this.text); console.log(this.context.text); console.log(this.context1.text); // нужное значение }, }, } objParent.objChild.needHere()