Fresheyeball
Fresheyeball

Reputation: 30035

javascript OOP get from parent object

How can I access the parent attribute of a child object like this?

    var foo = function foo(input){ this.input = input; };
    function bar(input){ return new foo(input); }
    foo.prototype = {
        baz : {
            qux : function(){
                alert(this.parent.input );
            }
        },
        corge : function(){
                alert(this.input );
        }
    }

bar('test').corge(); //alerts 'test'

bar('test').baz.qux(); //errors 'this.parent is undefined'

Upvotes: 0

Views: 1358

Answers (2)

Mike Samuel
Mike Samuel

Reputation: 120586

How can I access this.obj for a child object like this?

You can't.

There is one baz regardless of how many new foo there are, so there is no way to map from this which typically points to the singleton foo.prototype.baz to a specific instance of foo.

It looks like you probably meant to create a baz per instance of foo.

Try this

function foo(input) {
   this.baz = {
     parent: this,
     qux: quxMethod
   };
   this.input = input;
}
foo.prototype.corge = function () { alert(this.input); };
function quxMethod() {
  alert(this.parent.input);
}

Upvotes: 1

Naftali
Naftali

Reputation: 146360

Try defining baz like so:

  baz : (function(){
        var parent = this;
        return {
           qux : function(){
               alert(parent.obj);
           }
        }
    })()


Update:

I believe this will do what you want it to do:
Demo: http://jsfiddle.net/maniator/rKcwP/
Code:

var foo = function foo(input) {
    this.input = input;
};

function bar(input) {
    return new foo(input);
}
foo.prototype = {
    baz: function() {
        var parent = this;
        return {
            qux: function() {
                alert(parent.input);
            }
        }
    },
    corge: function() {
        alert(this.input);
    }
}

bar('test').corge(); //alerts 'test'
bar('test').baz().qux(); //alerts 'test'

Upvotes: 0

Related Questions