1

Is there a way, without explicitly calling the parent object by its instance name, to refer to the parent object's members? In the below example, the statement this.me refers to the me member of child. I know I can do something like var who = obj.me, but I was curious if there was a more implicit method of going about this?

var obj = {
    me: 'obj',
    child: {
        me: 'child',
        init: function() {
            var p = document.getElementById('console');
            var who = this.me;
            p.innerHTML = who;
        }
    }
};

obj.child.init();

http://jsfiddle.net/3CQ8f/4/

Cypher
  • 2,608
  • 5
  • 27
  • 41
  • No because otherwise with `var child = { };var parent1 = { child: child };var parent2 = { child: child };` what would "parent" on child return? Objets referencing each other form a graph, not a tree. – xavierm02 Aug 24 '12 at 18:49

1 Answers1

2

I don't think there's a built-in way to do this, but you could just create a reference to the parent in your object definition:

var obj = {
    me: 'obj'
};

obj.child = {
    me: 'child',
    parent: obj,
    init: function() {
        var p = document.getElementById('console');
        var who = this.parent.me;
        p.innerHTML = who;
    }
};
Travesty3
  • 14,351
  • 6
  • 61
  • 98