“TypeError: x is not a function” 即使代码有效

我在我的项目中的一个函数中遇到了上述错误,并将代码简化为以下内容。控制台成功记录了正确的结果,但仍然出现覆盖和错误。


有什么办法可以阻止这种情况发生吗?当它仍然正确运行时抛出错误似乎很奇怪。


func1 = (x,y) => {

  let result=(x+y)

  console.log(result)

}


func2 = x => {

  x()   // <= TypeError pointing to this not being a function

}



func2(func1(1,4)) // returns 5 but still getting TypeError


HUX布斯
浏览 268回答 2
2回答

心有法竹

func2接受一个函数作为参数,但你将它func1(1,4)作为参数传递,它的计算结果为undefined(因为func1不返回任何东西)。传递一个使用 所需参数调用的函数func,如果这是你想要做的:const func1 = (x, y) => {&nbsp; const result = x + y;&nbsp; console.log(result);}const func2 = x => {&nbsp; x();};func2(() => func1(1, 4));或者,如果您想获得更多功能,您甚至可以执行以下操作:const func1 = x => y => x + y;const func2 = x => x;console.log(func2(func1)(1)(4));

慕尼黑8549860

您已经将函数作为参数发送。传入的属性已经是一个函数。您无需再次键入“()”。const func1 = (x, y) => {const result = x + y;console.log(result);}const func2 = x => {&nbsp; x;};func2(func1(1, 4));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript