Javascript 使用 functionName() vs ()=>functionName 调用另一个函数的箭头

Javascript Arrow calling a function from another with functionName() vs ()=>functionName

假设您有一个 method/function 直到运行时才调用它。

const someMethod = () => {
  document.getElementById("myField").value = "Hello";
}

术语是什么,它们的执行方式有什么区别。

this.check(() => someMethod);

this.check(someMethod())

它们完全不同。

this.check(() => someMethod); 将传递一个回调,当被调用时(如果有的话),returns 一个函数。

this.check(someMethod()) 将立即someMethod 调用,然后将结果传递给 this.check 方法。

另一个未列出的选项是 this.check(() => someMethod());,它将在调用传递给 check 的回调时调用 someMethod

如果您担心 this 上下文,那么:

this.check(someObj.someMethod)

将导致 someMethod,在调用时,用 this 调用,无论 check 方法想要它是什么 .它保留someObj的上下文。相比之下

this.check(() => someObj.someMethod())

将导致 someMethodsomeObjthis 调用,无论 check 如何调用它。

因此,通常,为了安全起见,您需要 this.check(() => someObj.someMethod()) - 或提前绑定 someMethod,或者使用箭头函数而不是 [=31] 声明 someMethod =].

此处:this.check 接收回调作为其参数,returns someMethod 函数。

this.check(() => someMethod);

在这种情况下:this.check 接收 someMethod returns 的值作为其参数。

this.check(someMethod())