2

I have a small little problem in JavaScript. I would like to do the following:

var peter = {
  pet : spot
}

var spot = {
  owner : peter
}

The above code runs fine but peter.pet will be undefined. While spot.owner will be defined. IS there a better way then doing stuff like :

var peter = {
  pet : 'spot'
}

var spot = {
  owner : peter
}

peter.pet = eval(peter.pet)

Any insight will be appreciated...

2
  • 1
    Just one comment, because someone should say it: When I first read the question title, my immediate answer was "You shouldn't!" I'm sure you know that circular references are generally a bad programing habit. I'm not saying never use them, but in most cases they're a sign that you need to rethink the way your objects are set up. Commented Jul 22, 2013 at 19:11
  • 1
    In general I would agree with you 100%.But, there is certain instances where it is just easier to not try and flatten the structure. Commented Jul 22, 2013 at 19:14

3 Answers 3

5

Since objects are dynamic, just add pet later:

var peter = {
    // anything else you want to set
};

var spot = {
    owner : peter
};

peter.pet = spot;

EDIT - removed a bad attempt at adding a function to the peter object. To do it right, see Renan's post.

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

2 Comments

You ninja'ed me, so +1 for you.
I like this since its essentially what I decided to do. Its explicit and I don't need to go all OOP to do something simple.
3

Set the reference after you created spot:

var peter = {
  pet : undefined
}

var spot = {
  owner : peter
}

peter.pet = spot

Comments

2
var peter = {};
var spot = {owner: peter};
peter.pet = spot;

Alternatively, you could strenghen the typing:

PetOwner = function () {};
PetOwner.prototype.pet = null;

Animal = function (owner) {
    this.owner = owner;
    this.owner.pet = this;
};
Animal.prototype.owner = null;

var peter = new PetOwner();
var spot = new Animal(peter);

1 Comment

But your function setup was better than mine, so +1 to you! :-)

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.