Reputation: 4668
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')
}
}
]
}
Upvotes: 1
Views: 64
Reputation: 92854
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]);
Upvotes: 1
Reputation: 6698
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]
}
];
Upvotes: 0
Reputation: 2132
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 ]
Upvotes: 2