0

I'm trying to use the this keyword to access the owner object. If I execute the following code:

var object1 = {
    variable1: 5
}
object1.method1 = function() {
    return 6;
}
object1.object2 = {
    x: object1.variable1.toString() + "," + object1.method1()
}
console.log(object1.object2.x);

I receive the correct output: 5,6. But, if I substitute the instruction:

x: object1.variable1.toString() + "," + object1.method1()

with the instruction:

x: this.variable1.toString() + "," + this.method1()

I receive the error message: this.variable1 is undefined. I guess this is due to the this keyword referring to object2 instead of object1. Is there a more elegant way to refer to object1 (which is the object that has object2 as a member)?

0 Answers0