我收到错误
未捕获的TypeError:无法读取未定义的属性'render'
当我调用函数listView.render()
感谢您的帮助
var model = {
// the array with cats names
cats: ['mew', 'meo', 'meaw', 'memaw', 'mesaw', 'metaw'],
// The array of cats objects
Cats: []
}
var oct = {
// selecting the list on the left of the container
catsList: function () {
return document.querySelector('#catsList');
},
//selecting the cat display div
catsDisplay: function () {
return document.querySelector('#catsDisplay');
},
// creating the Cat object and push it to the Cats array
addCat: (function (arr) {
for (var i = 0; i < arr.length; i++) {
model.Cats.push((function (n) {
return {
name: n,
photo: n + '.jpg',
score: 0
};
}(arr[i])));
listView.render(model.Cats[i]);
};
}(model.cats))
}
var listView = {
render: function (CatObj) {
oct.CatList.innerHTML = "<div id='"+CatObj.addCat.name+"'>ss</div>"
}
}
答案 0 :(得分:0)
listView
正在悬挂,并设置为undefined
。所以在这里
listView.render(model.Cats[i]);
,listView
为undefined
答案 1 :(得分:0)
在声明之前,您无法使用listView。试试这个:
var model = {
// the array with cats names
cats: ['mew', 'meo', 'meaw', 'memaw', 'mesaw', 'metaw'],
// The array of cats objects
Cats: []
}
var listView = {
render: function (CatObj) {
//oct.CatList.innerHTML = "<div id='"+CatObj.addCat.name+"'>ss</div>"
}
}
var oct = {
// selecting the list on the left of the container
catsList: function () {
return document.querySelector('#catsList');
},
//selecting the cat display div
catsDisplay: function () {
return document.querySelector('#catsDisplay');
},
// creating the Cat object and push it to the Cats array
addCat: (function (arr) {
for (var i = 0; i < arr.length; i++) {
model.Cats.push((function (n) {
return {
name: n,
photo: n + '.jpg',
score: 0
};
}(arr[i])));
listView.render(model.Cats[i]);
};
}(model.cats))
}
var listView = {
render: function (CatObj) {
oct.CatList.innerHTML = "<div id='"+CatObj.addCat.name+"'>ss</div>"
}
}
答案 2 :(得分:0)
当你将函数声明为变量时,它们是在它们的位置创建的,所以在这种情况下你在调用它之后声明了listView
如果您希望listView可用,无论它在何处更改为常规功能,如
function listView() {
}
由于功能将在运行时提升到顶部。
答案 3 :(得分:0)
在CatList
对象上似乎没有名为oct
的属性。你也没有调用这个函数。尝试用oct.catsList
代替oct.CatList
,调用函数。同时将Cats
更改为_Cats
,将IIFE替换为返回可以调用的函数
var model = {
// the array with cats names
cats: ['mew', 'meo', 'meaw', 'memaw', 'mesaw', 'metaw'],
// The array of cats objects
_Cats: []
}
var oct = {
// selecting the list on the left of the container
catsList: function() {
return document.querySelector('#catsList');
},
//selecting the cat display div
catsDisplay: function() {
return document.querySelector('#catsDisplay');
},
// creating the Cat object and push it to the Cats array
addCat: (function(arr) {
return function() {
for (var i = 0; i < arr.length; i++) {
model._Cats.push({
name: i,
photo: i + '.jpg',
score: 0
});
listView.render(model._Cats[i]);
};
}
}(model.cats))
}
var listView = {
render: function(CatObj) {
oct.catsList().innerHTML += "<div id='" + CatObj.name + "'>ss</div>"
}
}
oct.addCat()
<div id="catsList">
</div>
<div id="catsDisplay">
</div>
jsfiddle https://jsfiddle.net/8u60bcsv/1/