我有一个与此相关的GlobalFunction.js文件。
function day(day) {
switch(day) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
}
function month(month) {
switch(month) {
case 0:
return "January";
case 1:
return "February";
case 2:
return "March";
case 3:
return "April";
case 4:
return "May";
case 5:
return "June";
case 6:
return "July";
case 7:
return "August";
case 8:
return "September";
case 9:
return "October";
case 10:
return "November";
case 11:
return "December";
}
}
function styleTime(time) {
time = time[1].split(':');
// fetch
var hours = Number(time[0]);
var minutes = Number(time[1]);
var seconds = Number(time[2]);
// calculate
var timeValue;
if (hours > 0 && hours <= 12) {
timeValue= "" + hours;
} else if (hours > 12) {
timeValue= "" + (hours - 12);
} else if (hours == 0) {
timeValue= "12";
}
timeValue += (minutes < 10) ? ":0" + minutes : ":" + minutes; // get minutes
timeValue += (hours >= 12) ? " P.M." : " A.M."; // get AM/PM
return timeValue;
}
function nth(d) {
if (d > 3 && d < 21) return 'th';
switch (d % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
function styleDate(date) {
var verifyDay = new Date(date[0]);
var dayOfWeek = day(verifyDay.getDay()); //prints monday, tuesday, wednesday, etc
var year = verifyDay.getFullYear(); // prints the year
var month = month(verifyDay.getMonth());
var day = verifyDay.getDate();
var date = day + nth(verifyDay.getDate());
return dayOfWeek + ", " + month + " " + date + " " + year;
}
export function styleDateTime(dateString) {
var dateTime = dateString.split(" ");
return styleDate(dateTime) + " at " + styleTime(dateTime);
}
// default export
export default function() {
return 'default';
}
我像这样将其导入到js文件中。
import { styleDateTime } from "../GlobalFunctions"
我这样使用它:
{styleDateTime(array.date)}
在styleDate函数中,它告诉我day is not a function
。为什么?
答案 0 :(得分:2)
这是因为day
中的本地styleDate
是shadowing外部定义的函数。将其重命名为其他名称。
如果您认为它不应该被遮盖,因为它是在第一次使用后定义的,JavaScript applies hoisting会将所有声明移到函数的开头,将它们设置为undefined,直到以后进行设置。
function styleDate(date) {
...
var myDay = verifyDay.getDate();
var date = myDay + nth(verifyDay.getDate());
...
答案 1 :(得分:2)
因为在styleDate
方法中,您正在创建一个与day同名的新变量,所以这就是您无法访问day方法的原因。使用其他变量名称,它将起作用。
这样写:
function styleDate(date) {
var verifyDay = new Date(date[0]);
var dayOfWeek = day(verifyDay.getDay()); //prints monday, tuesday, wednesday, etc
var year = verifyDay.getFullYear(); // prints the year
var month = month(verifyDay.getMonth());
// here
var new_day = verifyDay.getDate();
var date = new_day + nth(verifyDay.getDate());
return dayOfWeek + ", " + month + " " + date + " " + year;
}