0

Given the following object:

var myObj = {
    fname: 'John',
    lname: 'Doe',
    values: {
        get fullName() {
            return this.fname + ' ' + this.lname
        }
    }
};

When trying to access myObj.values.fullName, undefined undefined is returned because the context of this is set to myObj.values, not myObj.

Is there a way to change that? I tried every combination of bind I can think of, but most of the time this just results in syntax error because fullName isn't a regular function.

Sven
  • 12,997
  • 27
  • 90
  • 148

3 Answers3

1

You cannot access parent objects in Javascript. Do you need to nest the getter within the values element? The following would work just fine:

var myObj = {
    fname: 'John',
    lname: 'Doe',
    get fullName() {
        return this.fname + ' ' + this.lname
    }
};

alert(myObj.fullName)
Community
  • 1
  • 1
BlueRaven
  • 31
  • 3
1

You can access to parent object properties only by myObj.fname and myObj.lname.

var myObj = {
    fname: 'John',
    lname: 'Doe',
    values: {
        get fullName() {
            return myObj.fname + ' ' + myObj.lname
        }
    }
};
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
1

Replace "this" with the name of the object

OPTION 1:

var myObj = {
    fname: 'John',
    lname: 'Doe',
    values: {
        get fullName() {
            return myObj.fname + ' ' + myObj.lname
        }
    }
};

Another alternative:

OPTION 2:

var myObj = {
    fname: 'John',
    lname: 'Doe',
    values: {
        get fullName() {
            return this.parent.fname + ' ' + this.parent.lname
        }
    },
    init: function(){
        this.values.parent = this;
        delete this.init; 
        return this;
    }
}.init()