Access other properties of the same object

1

I have an object where I save data to build a view and I want to know if there is any way to access other properties of that object from another property in the same object

I tried this but it does not work

var obj = {

  template: '
  
  Nombre | Edad <br>
  ${this.names.name1} | ${this.age.age1}<br>
  ${this.names.name2} | ${this.age.age2}<br>
  ${this.names.name3} | ${this.age.age3}<br>
  
  ',
  names: {
    name1: 'Emmett',
    name2: 'Paola',
    name3: 'Mushi'
  },
  age: {
    age1: 8,
    age2: 20,
    age3: 3
  }

}

document.write(obj.template);
    
asked by Emiliano Pamont 20.09.2018 в 04:50
source

1 answer

2

There is a key concept for this detail, JavaScript has no block scope (object declaration) , but a function , when referencing this in reality refers to the object window which is the context where the object was called.

There may be two solutions at least for this detail

Define this property outside the object declaration

var obj = {
  names: {
    name1: 'Emmett',
    name2: 'Paola',
    name3: 'Mushi'
  },
  age: {
    age1: 8,
    age2: 20,
    age3: 3
  }

}
obj.template =  '
  Nombre | Edad <br>
  ${obj.names.name1} | ${obj.age.age1}<br>
  ${obj.names.name2} | ${obj.age.age2}<br>
  ${obj.names.name3} | ${obj.age.age3}<br>'

document.write(obj.template);

Or use a getter () what if it links to a function , so the reserved word this , will refer to the object.

var obj = {
  get template() { return  '
  Nombre | Edad <br>
  ${this.names.name1} | ${this.age.age1}<br>
  ${this.names.name2} | ${this.age.age2}<br>
  ${this.names.name3} | ${this.age.age3}<br>
  '},
  names: {
    name1: 'Emmett',
    name2: 'Paola',
    name3: 'Mushi'
  },
  age: {
    age1: 8,
    age2: 20,
    age3: 3
  },
}


document.write(obj.template);
  

Note that trying to assign a value to template will not change it. What   if you can do it is eliminate using delete

    
answered by 20.09.2018 / 07:25
source