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

});
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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.

1 Comment

No, that won't give access to outer's parent, and certainly not parent.name of the p object inside the inner() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.