I have an object where I store data to build a view and I want to know if there is a way to access other properties of that object from another property on the same object
I tried this
but it doesn't 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);
There is a key concept for this detail, JavaScript does not have a block scope (object declaration) , but rather a function scope , when it refers to
this
it actually refers to the objectwindow
that is the context where the call to the object was made.There may be two solutions at least for this detail
Defining that property outside of the object's declaration
Or use a getter() which if linked to a function, so the keyword
this
, will reference the object.