Reputation: 1642
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();
});
Upvotes: 0
Views: 117
Reputation: 3098
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.
Upvotes: -1
Reputation: 147553
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.
Upvotes: 2