代码如下:
<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>
Run Code Online (Sandbox Code Playgroud)
这将抛出:
"未捕获的TypeError:对象不是函数"
如果我将匿名函数调用/调用包装在另一组括号中,它将执行警报,但仍然给我一个错误.如果我在"var postTypes"定义之后放置一个分号,那么它将完全没问题.
我被引导相信javascript不需要分号,所以我猜测有一些奇怪的函数应用关联规则,我还没有完全理解.为什么我收到此错误?
ken*_*ytm 80
Javascript确实需要分号,只是当代码在没有它的情况下变为语法错误时,解释将在换行符时插入它.
不幸的是,代码
var a = new B(args)(stuff)()
Run Code Online (Sandbox Code Playgroud)
是不是一个语法错误,所以没有;将被插入.(可以运行的一个例子是
var answer = new Function("x", "return x")(function(){return 42;})();
Run Code Online (Sandbox Code Playgroud)
为了避免这样的意外,训练自己总是结束一个声明;.
(*:只是一个拇指规则.并非总是如此.插入规则要复杂得多.这个关于分号插入的博客页面有更多细节.)
CMS*_*CMS 17
您的代码遇到自动分号插入(ASI)过程未发生的情况.
你永远不应该依赖ASI.您应该使用分号来正确分隔语句:
var postTypes = new Array('hello', 'there'); // <--- Place a semicolon here!!
(function() { alert('hello there') })();
Run Code Online (Sandbox Code Playgroud)
您的代码实际上是在尝试调用数组对象.
我得到了一个类似的错误,我花了一段时间才意识到,在我的情况下,我将数组变量命名为payInvoices,函数也是payInvoices.它混淆了AngularJs.一旦我将名称更改为processPayments(),它终于奏效了.只是想分享这个错误和解决方案,因为我花了很长时间来弄明白这一点.
我在React 中遇到了这个问题:当它是默认导出时,我尝试解构并使用命名导出,例如:
// module.js
const myFunction = () => null
export default myFunction
Run Code Online (Sandbox Code Playgroud)
// component.js
// THIS WAS WRONG:
// import { myFunction } from './module'
// SHOULD BE THIS:
import myFunction from './module'
Run Code Online (Sandbox Code Playgroud)