Traversing an object and its properties

1

Assuming I have this piece of code:

let obj = {
  lang: {
    hi: 'Olá, mundo!'
  },

  engine: {
    functions: {
      init: function () {
        return this.lang.hi;
      }
    }
  }
};

console.log(obj.engine.functions.init());

How do I make the function obj.engine.init() work, that is, get to the property obj.lang.hi , by the function mentioned above.

    
asked by anonymous 17.09.2017 / 15:41

1 answer

2

Access to the object through obj.engine.functions.init() is correct. The problem is in the code inside the init function:

init: function () {
    return this.lang.hi;
}

That uses this as if it were obj when in fact it refers to functions itself. If we change this access by 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 not actually access the object that contains init , ie the parent object from within init natively.

A solution would be to refer to 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 create in functions a reference to obj with a kind of initialization 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());
    
17.09.2017 / 17:35