我正在使用OOP构建一个小日历,这是可行的,但每当我在另一个js文件中调用我的新Calendar()时,它会抱怨日历没有定义,我无法理解为什么会这样。
一些代码: 的index.html
<html>
<head>
<script src="monthData.js"></script>
<script src="month.js"></script>
</head>
<body>
<table>
<tbody id="table">
<tr id="year"></tr>
<tr>
<td id="prev-month"> Prev</td>
<td id="month"></td>
<td id="next-month"> Next</td>
</tr>
<tr id="days-of-week"></tr>
</tbody>
</table>
<script src="currentCal.js"></script>
</body>
</html>
month.js
window.wca = {}
};
(function() {
wca.today = new Date();
wca.currentYear = wca.today.getFullYear();
wca.currentMonth = wca.today.getMonth();
function Calendar(year, month){
this.year = wca.currentYear;
this.month = wca.currentMonth;
}
wca.Calendar.prototype.createCalendar = function(){
wca.currentDayOfWeek = wca.today.getDay();
wca.firstDay = new Date(wca.currentYear, wca.currentMonth, 1); //first day of current month
wca.firstDayOfWeek = daysLabel[wca.firstDay.getDay() - 1]; // first dayOfTheWeek of current month
wca.firstDayOfWeekNumber = wca.firstDay.getDay();
wca.showMonth = monthNamesArray[wca.currentMonth]; //current month string
wca.showWeekDay = daysLabel[wca.currentDayOfWeek - 1]; //current day of the week
wca.totDayInMonth = daysPerMonth[wca.currentMonth]; //how many days are in the current month
//Leap years
if (wca.currentMonth == 1) {
if((wca.currentYear % 4 == 0 && wca.currentYear % 100 != 0) || wca.currentYear % 400 == 0){
wca.totDayInMonth = 29;
}
}
var Htmltable = document.getElementById('table');
var year = document.getElementById('year');
var month = document.getElementById('month');
var daysOfWeek = document.getElementById('days-of-week');
year.innerHTML = '<td>'+ wca.currentYear +'</td>';
month.innerHTML = '<td>'+ wca.showMonth +'</td>';
for(i = 0; i < daysLabel.length; i++)
daysOfWeek.innerHTML = daysOfWeek.innerHTML + '<td>'+ daysLabel[i] +'</td>';
var html = '';
var day = 1;
for(i = 1; i <= 6; i++){ //6 rows
html += '<tr id="days-row">';
for(j = 1; j <= 7; j++){ //7 coloumns
html += '<td>';
if(day <= wca.totDayInMonth && (i > 1 || j >= wca.firstDayOfWeekNumber )){
html += day;
day++;
} else {
html += ' ';
}
html += '</td>';
}
if(day >= wca.totDayInMonth){
break;
}
html += '</tr>';
}
Htmltable.innerHTML += html + '</tr>';
}
})();
currentCal.js
window.wca = {};
(function() {
var currentCal = new Calendar(wca.currentYear, wca.currentMonth);
currentCal.createCalendar();
})();
所以,如果我把currentCal中的内容放在month.js中,一切正常,否则我会得到未定义的错误。 这是为什么? 因为在我的Html中我在month.js和currentCal.js之前链接,我认为它应该已经知道什么是Calendar();是
答案 0 :(得分:0)
看起来像是一个范围问题。你能尝试一下“var wca = {};”在month.js中,只在currentCal.js中使用它(没有window.wca = {};)?
编辑:他正在调用另一个文件中的闭包内的“新日历”,因此它不在另一个文件的全局范围内。他必须删除闭包“(function(){...})”以在全局范围内声明这些变量,并且可以从其他文件访问。