0

Is there a way to access the Parent's attribute from inner() without its reference being passed explicitly to it (as I have to do in this code) ?

Here is my javascript code :

function Parent() {
return {
    outer: {
        parent: null,  //I want to avoid this
        name: 'outer',
        inner: function() {
            console.log(this.name);
            console.log(this.parent.name);   //how to access parent.name ?
        }
    },

    name: 'parent'

};
}

$(document).ready(function() {

var p = new Parent();
p.outer.parent = p;  //I want to avoid this
p.outer.inner();

});
Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
Supra
  • 1,612
  • 1
  • 18
  • 36

2 Answers2

2

Is there a way to access the Parent's attribute from inner() without its reference being passed explicitly to it (as I have to do in this code) ?

No. There is no structure to objects other than name/value pairs, an object has no knowledge of things that reference it. Relationships are created entirely by assigning values to properties and work only in one direction: from a reference to an object.

The object literal:

var a = {foo: {bar:'bar'}};

is identical to:

var a = {};
a.foo = {bar:'bar'};

which is identical to:

var a = new Object();
var b = new Object();
b['bar'] = 'bar';
a['foo'] = b;

and any number of other similar formulations.

RobG
  • 142,382
  • 31
  • 172
  • 209
-1

You can ommit the p assignment by this:

function Parent() {
return {
    outer: {
        parent: this, //keep reference
        name: 'outer',
        inner: function() {
            console.log(this.name);
            console.log(this.parent.name);   //how to access parent.name ?
        }
    },

    name: 'parent'

};
}

$(document).ready(function() {

    var p = new Parent();
    p.outer.inner();

});

But I guess it's not what you need.

Radek Pech
  • 3,032
  • 1
  • 24
  • 29
  • No, that won't give access to outer's parent, and certainly not `parent.name` of the `p` object inside the `inner()` function. – user13500 Apr 02 '14 at 13:45