我刚刚学习 ES6,了解了箭头函数。我正在检查一个现有文件并一一转换函数。我已经转换了许多函数,除了 1 之外,所有函数都像以前一样工作。
这样做,我可以调用page
来获取当前文件名
let textArr = getPage.textArr;
let headingArr = getPage.headingArr;
const page = getPage.filename;
function getPage() {
const url = window.location.pathname,
fileWithExtension = url.substring(url.lastIndexOf('/')+1),
filename = fileWithExtension.split('.').slice(0, -1).join('.')
;
if (filename == "foo") {
textArr = [
`Text`,
`Text`
];
headingArr = null;
return {filename, textArr, headingArr}
}
}
保持一切不变,转换为箭头函数,然后在控制台中调用page
,我得到:
getPage is not defined at line 1
const getPage = () => {
const url = window.location.pathname,
fileWithExtension = url.substring(url.lastIndexOf('/')+1),
filename = fileWithExtension.split('.').slice(0, -1).join('.')
;
if (filename == "foo") {
textArr = [
`Text`,
`Text`
];
headingArr = null;
return {filename, textArr, headingArr}
}
}
最佳答案
这是一个提升问题。默认情况下,函数会被提升。分配给变量的箭头函数不会发生这种情况。如果你想让它起作用,你需要在调用它之前移动 const 定义。像这样:
const getPage = () => {
const url = window.location.pathname,
fileWithExtension = url.substring(url.lastIndexOf('/')+1),
filename = fileWithExtension.split('.').slice(0, -1).join('.')
;
if (filename == "foo") {
textArr = [
`Text`,
`Text`
];
headingArr = null;
return {filename, textArr, headingArr}
}
}
let textArr = getPage().textArr;
let headingArr = getPage().headingArr;
const page = getPage().filename;
关于javascript - 函数转换为箭头函数 - 函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54075180/