1

I declare Homebrew as a dependency for cask and referred to homebrew by this.homebrew[0]. Is anything like this possible with JavaScript?

var data = {
  homebrew: [
    {
      title: "Homebrew",
      dependencies: [],
      install: function() {
         console.log('homebrew')
      }
    },
    {
      title: "Cask",
      dependencies: [
         this.homebrew[0]
      ],
      install: function() {
         console.log('cask')
      }
    }
  ]
}
3
  • data should be an object in your case. Besides, how dependencies is used in further logic ? Commented Jan 30, 2017 at 21:27
  • dependencies should image the whole object titled homebrew Commented Jan 30, 2017 at 21:32
  • you can't do it in a single-step object literal - it's possible if you use multiple step initialisation Commented Jan 30, 2017 at 21:34

3 Answers 3

2

This is possible. One thing you can do is create your objects outside of the array, and set up references that way, such as:

var Homebrew = { title: "Homebrew" }
var Cask = { title: "Cask", dependencies: [Homebrew] }
var data = [ Homebrew, Cask ]
Sign up to request clarification or add additional context in comments.

Comments

1

The solution using Javascript get syntax(defining a getter):

var data = {
  homebrew: [
    {
      title: "Homebrew",
      dependencies: [],
      install: function () {
        console.log('homebrew')
      }
    },
    {
      title: "Cask",
      get dependencies() {   //  <-- getter function
        return [data.homebrew[0]]
      },
      install: function () {
        console.log('cask')
      }
    }
  ]
};

console.log(data.homebrew[1].dependencies[0]);

3 Comments

I think this is an unsafe approach. If the homebrew array gets rearranged the dependencies property will continue to return the zeroth item, breaking the dependency graph.
It also breaks one of my cardinal rules - that an object should never internally refer to itself by the name of the variable to which it has been assigned.
re: the latter comment, try var x = data; data = {}; console.log(x.homebrew[1].dependencies) - you now have a broken object
0

One possibility is to use a separate dependency object.

var data = {
  homebrew: [
    {
      title: "Homebrew",
      dependencies: [],
      install: function() {
         console.log('homebrew')
      }
    },
    {
      title: "Cask",
      dependencies: [
         this.homebrew[0]
      ],
      install: function() {
         console.log('cask')
      }
    }
  ]
};

var dependencies = [
  {
    data.homebrew[0],
    data.homebrew[1]
  }
];

Comments

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.