Today and colleagues saw a simple JavaScript code, but was tortured crazy, a long time to find the problem.
Code Listing 1:
<script>var gisService = (function(window) { return { name:function () { alert(1); } };})(this);gisService.name();</script>
There is no problem with this notation, especially for Java developers, in Java we typically write Java classes or functions in such a way that braces are aligned. But this JavaScript code will get an error under chrome:
Uncaught syntaxerror:unexpected token (.
Code Listing 2:
<script>var gisService = (function(window) { return { name:function () { alert(1); } };})(this);gisService.name();</script>
Code 2 is almost identical to code 1, and the only difference is the curly braces that follow the return. But code 2 can work under Chrome. I don't know why, but obviously this is a bug in JavaScript design, because code 1 and code 2 are just formatting and typography.
Code Listing 3:
<script>var gisService = (function(window) { function name() { alert(1); } return { name:name };})(this);gisService.name();</script>
Running code 3 under Chrome will cause an error:
Uncaught Typeerror:cannot Read Property ' name ' of undefined.
This article also mentions a similar problem: put the brace {at the end of a line instead of at the beginning of the next line, because it avoids a horrible design error in the return statement of the JavaScript.
JavaScript has an automatic fix mechanism-automatically inserts a semicolon complement when a program may be defective, but this mechanism is unreliable and often obscures some errors.
Like what:
return{ hello:"world";};
The normal understanding is to return a literal composition of the object.
But if you write this:
return{ hello:"world"};
The Auto-fill plenary of JavaScript turns the above code into:
return;{ hello:"world"};
Actually returns a undefined with no hint of this error.
Knowing this auto-completion mechanism makes it easy to understand why code 3 is an error.
Here are a few ways to define a function, only the way 1 is wrong. This can also explain why the code 1 will be an error.
// 方式1:错误{ name:function(){ }};// 方式2:正确var obj = { name:function(){ }};//方式3:正确({ name:function(){ }});//方式4:正确function name(){}{ name:name};
Is the return line also wrong? Design flaws in JavaScript return