为什么必须在调用方函数上方声明箭头函数

问题描述

一个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未定义,也不会如果我使用this关键字来定位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编译错误而无法正常工作,但这确实是我的陪同错误-'foo' was used before it was defined,确实这意味着不建议这样做吗?

这是为什么,这意味着我们必须始终在caller函数上方声明arrow函数吗?有其他解决方法吗?

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类中声明arrow函数时,如果调用函数也带有this关键字,则仅在调用函数也为arrow函数的情况下,它可以与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();

解决方法

您声明的任何变量(Restaurantlet变量除外)或在全局上下文(例如,直接在test.js中)定义的函数都将附加到Window对象。所以,当你写的时候,

const

// test.js function myCaller() { foo('hello world'); // this works! this.foo('hello world'); // this works! } function foo(text) { console.log('foo called!',text); } myCaller() myCaller都作为属性附加到窗口对象。现在,您可以直接引用它们,就像foo(此处是隐式的)或foo()甚至是this.foo()。由于js使用提升,因此这些变量或函数首先附加到上下文,然后开始执行。

但是window.foo()const未附加到Window对象(否则,它们将随处可见,其行为与let完全一样)。所以当你写

var

JavaScript引擎会扫描整个脚本,以查看是否定义了任何变量或函数。在此提升阶段,如果找到// test.js function myCaller() { foo('hello world'); this.foo('hello world'); } const foo = (text) => { console.log('foo called!',text); } myCaller(); const,它将为其分配内存,但不会使它们成为Window对象的一部分。因此,当您在全局上下文中引用let时,它是指窗口对象,而this不是窗口对象的属性。这就是为什么即使将foo放在const foo定义之上,也行不通的原因。

对于类,如果您尝试直接调用myCaller而不引用它,它将尝试从封闭的上下文中访问它,在您的示例中未定义它。因此会引发错误。如果您在类外使用foo()或直接将其定义为foo()来定义另一个var,那么它将起作用。

foo = (text) => ...可能并不总是引用全局上下文。函数和类可以具有自己的自定义上下文,而this可以引用该上下文。但是,当没有定义自定义上下文时,函数或类,全局上下文将是this关键字所指的上下文。this在严格模式下默认情况下未为函数和类定义,this有几个注意事项考虑。