tags:

views:

96

answers:

2

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

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. I hope someone can give me the answer to why I am getting this error.

Thanks.

+2  A: 

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

Unfortunately, the code

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

KennyTM
Or: To avoid surprises like this, train yourself to write clean readable code (which should always apply) and know the general ASI rules... it really is no different than "knowing" how closures in JS work.
pst
+1  A: 

Your code experiences a case where the Automatic Semicolon Insertion (ASI) process don't happens.

You should never rely on ASI, you should use semicolons to properly separate statements:

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

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

Your code before, was actually trying to invoke the array object.

CMS
One way to fix the issue, but I can't get behind the Crockford-club.
pst
@pst: Let me rephrase, I'm not in the Crock's-club *at all* :)
CMS
@pst: I think you'll enjoy this quiz: http://asi.qfox.nl/ ;)
CMS
@CMS In that case I apologize for the harsh words :(
pst
@CMS I did enjoy the quiz. ASI is indeed terribly confusing with icky-code!
pst