【发布时间】:2016-06-10 03:50:07
【问题描述】:
我得到了错误
未捕获的类型错误:无法读取未定义的属性“渲染”
当我调用函数listView.render()时它在第29行
感谢您的帮助
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>"
}
}
【问题讨论】:
-
addCat代码包装在 IIFE 中,因此会立即执行。这是一个非常糟糕的设计,非常出乎意料,也是为什么listView在那时未定义的原因。你至少应该有像oct.init()这样的东西来启动事情。您的整个代码实际上是非常糟糕的 IMO(无意冒犯),到处都有紧密的耦合和隐藏的依赖关系。例如,为什么 listView 不封装它自己的列表 DOM 元素......你不必从那里进入 oct。
标签: javascript arrays oop javascript-objects