我将Homebrew声明为cask的依赖项,并通过this.homebrew[0]
引用自制程序。用JavaScript可以做到这一点吗?
var data = {
homebrew: [
{
title: "Homebrew",
dependencies: [],
install: function() {
console.log('homebrew')
}
},
{
title: "Cask",
dependencies: [
this.homebrew[0]
],
install: function() {
console.log('cask')
}
}
]
}
答案 0 :(得分:2)
这是可能的。您可以做的一件事是在数组外部创建对象,并以这种方式设置引用,例如:
var Homebrew = { title: "Homebrew" }
var Cask = { title: "Cask", dependencies: [Homebrew] }
var data = [ Homebrew, Cask ]
答案 1 :(得分:1)
使用Javascript https://github.com/feross/buffer语法(定义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]);
&#13;
答案 2 :(得分:0)
一种可能性是使用单独的依赖对象。
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]
}
];