I have a couple of nested objects, where A is always a part of B.

May I use the following code to access owner's properties and methods?

function A( owner ) {
  this.value = function () { return owner.value() + 1 };
}

function B() {
  this.value = function () { return 1; };
  this.a = new A( this );
}

var b = new B();
alert( b.a.value() );

Actually, it works. But I would like to know whether it is correct or not.

link|improve this question
feedback

migrated from stackoverflow.com Feb 23 at 17:22

This question came from our site for professional and enthusiast programmers.

3 Answers

up vote 0 down vote accepted

You may consider to move the methods declaration from the constructors to the prototypes of the constructors. You will save memory if you have a lot of objects A and B, because in your sample for every object there will be a copy of the method inside of it. Moving a method declaration to the prototype will allow all objects to share a single copy of this method. But you will have to keep a reference to the "owner" in A (now you use closures to keep a reference to it).

link|improve this answer
feedback

That's fine, at least from the implementation standpoint. Do you have any specific concerns about this approach?

link|improve this answer
Thanks. Probably, the only concern is that I just do not understand how is that variable being stored in the instance. – mailgpa Feb 21 at 12:17
The other answer briefly explains it, I'll just reiterate. You can consider this as a special syntax. this.foo references a field of a new object whose prototype is A.prototype if your call site invokes new A() (as opposed to just A() or A.call(someObject), in which case this depends on the way the function is called). – Alexander Pavlov Feb 21 at 12:25
feedback

Actually, it works. But I would like to know whether it is correct or not.

It works because you create new instance of parent and access it there:

this.a = new A( this );

The correct way (for inheritence) is to set child's prototype and constructor:

A.prototype = new B();
A.prototype.constructor = A;

For more explanation, have a look at this question.

link|improve this answer
Well, I do not need class inheritance there. I need to access properties of parent object. – mailgpa Feb 21 at 12:13
1  
@mailgpa: Generally when you use the word parent, it also means it has child. If you are asking only in terms of nested objects or the way you have done it with no inheritance, then you are doing it fine. – Sarfraz Feb 21 at 12:15
Thanks, corrected my question. – mailgpa Feb 21 at 12:18
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.