博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何解决JavaScript中的“不是函数”错误
阅读量:2508 次
发布时间:2019-05-11

本文共 1837 字,大约阅读时间需要 6 分钟。

I write JavaScript without semicolons.

我写JavaScript没有分号。

And I really like that. The language is cleaner, in my opinion.

我真的很喜欢。 我认为这门语言比较干净。

You might not like that, and it’s understandable. But that’s the way it is.

您可能不喜欢它,这是可以理解的。 但这就是事实。

Semicolons are optional. We are not required to add them.

分号是可选的。 我们不需要添加它们。

Sometimes, however, we must pay attention. In particular, in Node.js we use require() to load external modules and files.

但是,有时我们必须注意。 特别是在Node.js中,我们使用require()加载外部模块和文件。

This can cause, in some cases, an error like this:

在某些情况下,这可能会导致如下错误:

TypeError: require(...) is not a function

That’s a weird error, right?

那是一个奇怪的错误,对吧?

Let’s look at how I got it.

让我们看看我是怎么得到的。

I required a library, and then I had to run some code at the root level and I created an immediately-invoked async function:

我需要一个库,然后我必须在根级别运行一些代码,然后创建了一个立即调用的异步函数:

const fs = require('fs')(async () => {  //...})()

JS does not see a semicolon after require(), and we start a line with a (, and JS thinks we’re trying to execute a function.

JS在require()之后看不到分号,我们以(开头,而JS认为我们正在尝试执行一个函数。

It consider require('fs') as the name of the function, which is something that could actually work if the module export returned a function.

它将require('fs')作为函数的名称,如果模块导出返回函数,则该函数实际上可以工作。

But it’s not, so we get that ...is not a function error.

但这不是,所以我们得到的...is not a function错误。

How do we fix it?

我们该如何解决?

We must add a semicolon. Somewhere.

我们必须添加一个分号。 某处。

This would work:

这将工作:

const fs = require('fs');(async () => {  //...})()

and also this would work:

而且这将工作:

const fs = require('fs');(async () => {  //...})()

It’s a little price we have to pay to avoid the use of semicolons everywhere.

为了避免在任何地方使用分号,我们必须付出一点代价。

Tip: is now a thing, you can use that instead of this structure, and it will prevent such errors.

提示:现在已成为现实,您可以使用它来代替此结构,这样可以防止此类错误。

翻译自:

转载地址:http://vomgb.baihongyu.com/

你可能感兴趣的文章
python编程 之 PyMysql包接口,python中如何使用数据库
查看>>
WinForm 简单蒙版实现控件遮盖
查看>>
ASP.NET MVC ValueProvider小结
查看>>
ES6之路第二篇:变量的解构赋值
查看>>
iOS6新特征:UICollectionView介绍
查看>>
分享一个基于Bootstrap的 ACE框架 入门(MVC+EF)
查看>>
增量关联规则挖掘—FUP算法
查看>>
spring相关—AOP编程—切入点、连接点
查看>>
animation_Frame动画图片轮播
查看>>
BZOJ 4195 - 离散化 + 并查集
查看>>
Oracle常用数据类型
查看>>
信息安全技术 作业5
查看>>
Java关键字final、static使用总结
查看>>
python文件_批量改名
查看>>
暑假集训(3)第一弹 -----还是畅通工程(hdu1233)
查看>>
php集成工具
查看>>
uestc 1855, dfs, 模拟
查看>>
Word Ladder II
查看>>
Binary Tree Level Order Traversal
查看>>
30+ Excellent Windows Phone 7 Development Tutorials
查看>>