javascriptobjectchild-objects

Trying to get an object to identify its parent object without passing the parent into the child's instance


I'm having troubles finding detailed information on this issue. I would like to instantiate Bar() within Foo() without having to pass a pointer to Foo(). Or some way for Bar() to know it's a child of Foo(). Is this possible? Or am I already using a sufficient method?

Basically, I'm trying to avoid a call like:

var bar1 = new Bar(this,someValue);

Below I have a rough example of the method I'm currently using.

function Bar(p,val) {
    var par = p,
        value = val;
    this.__defineGetter__("value", function() {
        return par.dun.value + value;
    });
}

function Dun(val) {
    var value = val;
    this.__defineGetter__("value", function() {
        return value;
    });
}

function Foo() {
    var dun = new Dun(15);
    var bar1 = new Bar(this, 10);
    var bar2 = new Bar(this, 20);
    this.__defineGetter__("dun", function() {
        return dun;
    });
    this.__defineGetter__("bar1", function() {
        return bar1;
    });
    this.__defineGetter__("bar2", function() {
        return bar2;
    });
}
var myFoo = new Foo();
myFoo.bar1.value;

Thanks.


Solution

  • No this is not possible, since there is no built in parent/child logic in JavaScript. They are just references to objects.

    Update

    oh sorry, I think I misunderstood your question. I´ve asked the same question some time ago: here. What you are trying to do, is to get the object that is "this" in the function that called the current function.

    The answer is: you can´t do it...

    But you could do it using the scope:

    function Dun(val) {
        var value = val;
        this.__defineGetter__("value", function() {
            return value;
        });
    }
    
    function Foo() {
        var dun = new Dun(15);
        var bar1 = new Bar(10);
        var bar2 = new Bar(20);
        this.__defineGetter__("dun", function() {
            return dun;
        });
        this.__defineGetter__("bar1", function() {
            return bar1;
        });
        this.__defineGetter__("bar2", function() {
            return bar2;
        });
        function Bar(val) {
            this.__defineGetter__("value", function() {
                return dun.value + val;
            });
        }
    }
    var myFoo = new Foo();
    myFoo.bar1.value;
    

    PS: Not related to your question, but nice to know: since

    function(val){}
    

    is the same as

    function(){
        var val = arguments[0];
    }
    

    you don`t have to create a new var and pass the arguments value to it. You can use the argument variable directly.