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

使用functionName()vs()=>;从另一个调用函数的Javascript箭头;函数名,javascript,arrow-functions,Javascript,Arrow Functions,假设您有一个直到运行时才想调用的方法/函数 const someMethod = () => { document.getElementById("myField").value = "Hello"; } 术语是什么?它们的执行方式有什么区别 this.check(() => someMethod); 及 他们完全不同 this.check(()=>someMethod)将传递一个回调,该回调在被调用时(如果有)返回一个函数 this.

假设您有一个直到运行时才想调用的方法/函数

const someMethod = () => {
  document.getElementById("myField").value = "Hello";
}
术语是什么?它们的执行方式有什么区别

this.check(() => someMethod);


他们完全不同

this.check(()=>someMethod)
将传递一个回调,该回调在被调用时(如果有)返回一个函数

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

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

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

this.check(someObj.someMethod)
调用时,将导致
someMethod
,并使用
check
方法所需的
this
进行调用。它不保留
someObj
的上下文。相比之下

this.check(() => someObj.someMethod())
将导致使用
someObj
this
调用
someMethod
,而不管
check
如何尝试调用它


所以,通常,为了安全起见,您需要
这个。提前检查(()=>someObj.someMethod())
-或绑定
someMethod
,或者使用箭头函数而不是
函数来声明
someMethod
,此处:
this。check
接收回调作为其参数,该参数返回
someMethod
函数

this.check(() => someMethod);
在本例中:
this.check
接收
someMethod
作为其参数返回的值

this.check(someMethod())

互联网上有很多详细介绍JavaScript函数的资源:@MartinBean当然有。我问了一个非常具体的问题,因为我找不到答案。不过,这不是编程问题。这是一个普遍理解的问题。以本网站应提出的问题类型为例。