Scroll over an object and its properties

Asked

Viewed 146 times

1

Supposing I had this piece code:

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

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

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

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

  • alters the this for the obj

1 answer

2


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());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.