DanRedux
DanRedux

Reputation: 9349

Nested objects referring to each other?

Suppose I have something like this:

network = {
  post: function(t) {
    console.log(t); }
  protocol: {
    init: function() {
      /* network.post("init") */ } } }

The commented part, how would I allow the network.protocol.init function to call network.post through some sort of relative link? How can network.protocol find networks variables?

Thanks. :)

Upvotes: 0

Views: 47

Answers (1)

Matt
Matt

Reputation: 75317

This is a limitation of object literal syntax; you just can't do it.

Your best option would be to reference network via a property on the protocol object, and add it immediately after declaring the object via object literal syntax;

network = {
  post: function(t) {
    console.log(t); }
  protocol: {
    init: function() {
      this.network.post("init") } } }

network.protocol.network = network;

... this works because the existance of the network property is deferred until the execution of init itself.

Upvotes: 1

Related Questions