【发布时间】:2020-08-23 05:46:22
【问题描述】:
在 javascript 文件中,当我使用 function 关键字声明函数时,我可以将函数放在调用者函数之后,例如
// test.js
function myCaller() {
foo('hello world'); // this works!
this.foo('hello world'); // this works!
}
function foo(text) {
console.log('foo called!', text);
}
myCaller()
但是如果我把foo变成一个箭头函数,并把它放在相同的位置,那么在myCaller函数中,它说foo没有定义,如果我使用@987654327它也不起作用@关键字来定位foo函数,我假设this是指全局/文档级别
// test.js
function myCaller() {
foo('hello world'); // es-lint warning: 'foo' was used before it was defined
this.foo('hello world'); // compilation error: foo is not defined
}
const foo = (text) => {
console.log('foo called!', text);
}
myCaller();
- 我错了,我认为不使用this 的第二种方法由于not defined 的javascript 编译错误而不起作用,但这实际上是我的eslint 错误-'foo' was used before it was defined,这是否意味着不建议这样做这样做?
为什么会这样?这是否意味着我们必须始终在 caller 函数上方声明箭头函数?有没有其他方法可以解决这个问题?
const foo = (text) => {
console.log('foo called!', text);
}
// test.js
function myCaller() {
foo('hello world'); // this works! no es-lint warning now
this.foo('hello world'); // no compilation error but there is a run-time error : 'this.foo is not a function'
}
myCaller();
另外,我发现当在javascript类中声明箭头函数时,它只能与this关键字一起使用,调用函数也是箭头函数,如果调用函数带有function关键字,这将不起作用...
// myTest.js
class myTest {
myCaller() {
foo('hello world'); // compilation error: foo is undefined
}
myCaller2 = () => {
this.foo('hello world'); //this works!
}
foo = (text) => {
console.log('foo called!', text);
}
}
new myTest().myCaller();
new myTest().myCaller2();
【问题讨论】:
-
与箭头无关,与
const的范围有关 -
另外,即使 const foo 高于 myCaller,
this.foo随后也会失败 - 因为 const 和 let 变量未添加到“全局”对象 -this可能是全局对象(窗口在浏览器上)在您的代码中 -
@JaromandaX 我应该删除
const吗?我无法删除const...如果我删除const,则会出现编译错误foo is not defined -
@BaruchMashasha 感谢您的链接,但我认为这在这里没有帮助,因为我没有执行
myCaller函数,因为它已经生成了编译错误,此外,为什么它在它起作用时使用function关键字但不用于箭头函数?
标签: javascript this arrow-functions function-declaration