我有一个cats
这样的对象:
var model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
],
currentCat: cats[0], //error here
}
当我尝试访问时cats[0]
,出现以下错误:ReferenceError: cats is not defined
如果我将其替换cats[0]
为this.cats[0]
以下错误:Uncaught TypeError: Cannot read property '0' of undefined
无法访问同一对象内的对象属性吗?还是应该在内部创建一个函数model
并currentCat
在其中初始化?
不,不可能。尝试以下方法:
var model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
]
}
model.currentCat = model.cats[0];
您无法在对象初始化之前使用它-因此,在您尝试设置的位置上currentCat
,您仍在“内部”初始化中,并且无法访问模型。
在此代码之后,模型将如下所示:
model = {
cats: [
{
name: "Fossie",
url: "",
count: 0
},
{
name: "Bootsie",
url: "",
count: 0
}
],
currentCat: {
name: "Fossie",
url: "",
count: 0
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句