Access to the object through obj.engine.functions.init()
is correct. The problem is in the code within the function init
:
init: function () {
return this.lang.hi;
}
Who uses the this
as if it were the obj
when it actually refers to the functions
. If we exchange this access for a return of a fixed value we see that it works:
let obj = {
lang: {
hi: 'Olá, mundo!'
},
engine: {
functions: {
init: function () {
return "Dentro de init"; //retornando agora uma string normal
}
}
}
};
console.log(obj.engine.functions.init());
You can’t actually access the object that contains the init
, or is the parent object from within the init
natively.
A solution would be referencing the object obj
directly with:
init: function () {
return obj.lang.hi;
}
Example:
let obj = {
lang: {
hi: 'Olá, mundo!'
},
engine: {
functions: {
init: function () {
return obj.lang.hi;
}
}
}
};
console.log(obj.engine.functions.init());
Another solution would be to functions
a reference to obj
with a sort of boot function:
let obj = {
lang: {
hi: 'Olá, mundo!'
},
iniciar: function() { //aqui função para construir a referencia
this.engine.functions.referenciaObj = this;
},
engine: {
functions: {
init: function () {
return this.referenciaObj.lang.hi; //acesso pela referencia interna
}
}
}
};
obj.iniciar(); //iniciar para que a referência exista
console.log(obj.engine.functions.init());
alters the
this
for theobj
– Pedro Pinto