Why does a results vary based on curly brace placement?

I have read this article, where an example is shown. Please explain why the code snippets below return different results due to changes in the placement of curly the braces.

Example with an opening curly brace { on new line.

function test()
{
  return
  { /* <----curly brace in new line */
    javascript: "fantastic"
  };
}

var r = test();
try {
  alert(r.javascript); // does this work...?
} catch (e) {
  alert('no - it broke: ' + typeof r);
}

test() returns undefined .

Example with an opening curly brace { on same line as return .

function test()
{
  return { /* <----inline curly brace */
    javascript : "fantastic"
  };
}

var r = test();
try {
  alert(r.javascript); // does this work...?
} catch (e) {
  alert('no - it broke: ' + typeof r);
}

test() returns an object.

Here is live example beware of curly braces.


That's one of the pitfalls of javascript: automatic semicolon insertion. Lines that do not end with a semicolon, but could be the end of a statement are automatically terminated, so your first example looks effectively like this:

function test()
{
  return; // <- notice the inserted semicolon
  { 
    javascript : "fantastic"
  };
}

See also http://javascript.crockford.com/code.html

In your second example you return an object (built by the curly braces) with the property javascript and its value of fantastic, effectively the same as this:

function test() {
    var myObject = new Object();
    myObject.javascript = "fantastic";
    return myObject;
}

Javascript doesn't require semicolons at the end of statements, but the drawback is that it has to guess where the semicolons are. Most of the time this is not a problem, but sometimes it invents a semicolon where you didn't intend one.

An example from my blog post about this (Javascript – almost not line based):

If you format the code like this:

function getAnswer() {
   var answer = 42;
   return
      answer;
}

Then it is interpreted like this:

function getAnswer() {
  var answer = 42;
  return;
  answer;
}

The return statement takes it's parameterless form, and the argument becomes a statement of it's own.

The same happens to your code. The function is interpreted as:

function test()
{
  return;
  {
    javascript : "fantastic"
  };
}

It's because javascript most often puts ";" at the end of each line, so basicly when you have return { in same line, javascript engine see that there will be something more, and when its in new line it thinks you forgot to put ";", and puts it for you.

链接地址: http://www.djcxy.com/p/25438.html

上一篇: NetBeans,关闭** ANY **自动缩进/自动格式化

下一篇: 为什么结果因大括号放置而异?