0

The following code is working as expected

obj = {
   go: function() { alert(this) }
}
obj.go(); // object
(obj.go)(); // object 
(a = obj.go)(); // window
(0 || obj.go)(); // window

but why error occurred when I comment the beginning two lines?

obj = {
   go: function() { alert(this) }
}
//obj.go(); // commented this line
//(obj.go)(); // commented this line
(a = obj.go)(); // window
(0 || obj.go)(); // window

I didn't change any of the code above, just comment two lines which are separate from others, then the browser gives me error information? Could anyone please clarify that for me? many thanks.

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
Huibin Zhang
  • 1,072
  • 1
  • 15
  • 30

2 Answers2

3

Without a semicolon, your second sample is parsed as

obj = { ... }(...)();

Since the object is not a function, you get an error when you try to call it.

Semicolons in Javascript are optional, and your first sample is invalid syntax without a semicolon, so it implicitly inserts a semicolon.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    "Since the object is not a function, you get an error when you try to call it." — That would happen, but there is another error that occurs before the code gets that far. – Quentin Oct 29 '14 at 16:05
  • @SLaks, does that mean I need to add ; on every expression manually? – Huibin Zhang Oct 29 '14 at 16:07
  • @bean That is a somewhat contentious issue. According to [Do you recommend using semicolons after every statement in JavaScript?](http://stackoverflow.com/q/444080/18192), Stackoverflow users tend to say yes. You can go a step further and use a linting tool (most popular would be [JSHint](http://www.jshint.com) and [JSLint](http://www.jslint.com)) to detect this kind of thing. – Brian Oct 29 '14 at 16:28
1

You have a ( immediately after the } so you are trying to call the result of evaluating the block as if it was a function.

Before you do that, however, you are trying to evaluate a = obj.go so it can be passed as an argument.

Since obj hasn't been defined yet (because the result of calling the "function" hasn't been passed to obj), it throws an error.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335