Javascript“Uncaught TypeError:object is not a function”相关性问题 [英] Javascript "Uncaught TypeError: object is not a function" associativity question

查看:585
本文介绍了Javascript“Uncaught TypeError:object is not a function”相关性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

<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>

这将抛出:


未捕获的TypeError:对象不是函数

"Uncaught TypeError: object is not a function"

如果我将匿名函数调用/调用包装在另一个函数中一组括号它将执行警报,但仍然给我一个错误。如果我在var postTypes定义之后放置一个分号,那么它将完全正常。

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 semi-colon after the "var postTypes" definition then it will completely fine.

我被认为javascript不需要分号,所以我猜测有一些奇怪的函数应用关联规则我还没有完全理解。为什么我会收到此错误?

I was led to believe that javascript does not require semi-colons, 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?

推荐答案

Javascript确实需要分号,只是解释会为您插入当代码变为没有它的语法错误时换行符。*

Javascript does require semi-colons, it's just that the interpret will insert it for you on line-breaks when the code becomes syntax-error without it*.

不幸的是,代码

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

语法错误,因此不会插入; 。 (可以运行的一个例子是

is not a syntax error, so no ; will be inserted. (An example which can run is

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

为了避免这样的惊喜,训练自己总是结束声明;

To avoid surprises like this, train yourself to always end a statement with ;.

(*:只是一个拇指规则。并非总是如此。插入规则很多更复杂。有关分号插入的博客页面有更多详细信息。)

(*: Just a thumb-rule. Not always true. The insertion rule is much more complicated. This blog page about semicolon insertion has more detail.)

这篇关于Javascript“Uncaught TypeError:object is not a function”相关性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆