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/

4

1 に答える 1

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;
    }
};
于 2012-08-24T18:30:19.137 に答える