简体   繁体   中英

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'

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);
}

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM