JavaScript "Uncaught TypeError: object is not a function" associativity question

The code is as follows:

<body>
<a href="javascript:;" id="test">hello</a>
</body>


<script type="text/javascript">
document.getElementById("test").addEventListener("click", function () {
test()
}, false)
function test() {
var postTypes = new Array('hello', 'there')
(function() { alert('hello there') })()
}
</script>

This will throw an:

"Uncaught TypeError: object is not a function"

If I wrap the anonymous function call/invocation in another set of parentheses it will execute the alert, but still give me an error. If I put a semicolon after the "var postTypes" definition then it will be completely fine.

I was led to believe that JavaScript does not require semicolons, so I'm making a guess that there is some weird associativity rules of function application that I am not fully understanding. Why am I getting this error?

499524 次浏览

JavaScript 确实需要分号,只是解释器会在可能的地方为你插入分号。

不幸的是,密码

var a = new B(args)(stuff)()

does 没有 result in a syntax error, so no ; will be inserted. (An example which can run is

var answer = new Function("x", "return x")(function(){return 42;})();

为了避免这样的意外,训练自己总是以 ;结束语句。


这只是经验法则,并不总是正确的。插入规则要复杂得多。这个关于分号插入的 博客主页有更多的细节。

您的代码遇到了 自动插入分号(ASI)进程没有发生的情况。

你不应该依赖 ASI。你应该使用分号来正确地分隔语句:

var postTypes = new Array('hello', 'there'); // <--- Place a semicolon here!!


(function() { alert('hello there') })();

您的代码实际上是在尝试调用数组对象。

我得到了一个类似的错误,我花了一段时间才意识到,在我的情况下,我命名了数组变量 付款发票和函数也 付款发票。它混淆了 AngularJS

一旦我改名为 (),它终于工作。

尝试在调用 JavaScript 文件中的函数体之前使用函数体。

我得到了同样的错误,花了一天半的时间试图找到一个解决方案。Naomi 的回答引导我找到我需要的解决方案。

我的输入(type = Button)有一个属性 name,该属性与 onClick 事件调用的函数名相同。一旦我改变了属性 name,一切都工作了。

<input type="button" name="clearEmployer" onClick="clearEmployer();">

改为:

<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">

我有这个错误时,编译和捆绑类型脚本代码与 网络包。它将 export class AppRouterElement extends connect(store, LitElement){....}编译成 let Sr = class extends (Object(wr.connect) (fn, vr)) {....},这似乎是错误的,因为缺少逗号。与 Rollup 捆绑时,没有错误。

我在 做出反应中遇到了这个问题: 我尝试使用 毁灭,并在默认导出时使用命名导出,例如:

// module.js
const myFunction = () => null
export default myFunction
// component.js
// THIS WAS WRONG:
// import { myFunction } from './module'
// SHOULD BE THIS:
import myFunction from './module'