-4

Now that I have my other questions answered, this function isn't working. What's wrong?

Weird JavaScript statement, what does it mean?

How to handle click event in javascript?

function myFunc() {
    return
    {
        obj = this;
    };
}
Community
  • 1
  • 1
Stack Guru
  • 873
  • 2
  • 8
  • 7
  • 1
    Trying to return an object from my function. – Stack Guru Mar 28 '11 at 18:44
  • I'm tempted to flag this question to be closed, but several people have already answered it. You have two syntax errors in that function . Fix both of those, and it'll work as expected. – Mark Bessey Mar 28 '11 at 18:48

3 Answers3

6

The syntax to create an object literal is:

{ foo: bar }

not

{ foo = bar }

Additionally, in JavaScript a new line can terminate a statement. By placing a new line after the return you are returning undefined and the object literal code is never reached. JSLint can pick up on this type of problem.

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

Your function is not working due to how JavaScript auto-adds semicolons.

Your return statement is being read by JavaScript as:

return;
{
    obj: this;
};

You need to put the { on the same line as return:

return{
    obj: this;
};

Also, objects need to be {name: value}.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
5

It's because of semicolon injection.

This:

return
  { myProperty: "hello world" };

Is parsed like this:

<< return statement >>
<< pointless object literal expression >>

And not as:

<< return statement with return value expression >>

To return an object value, your code has to look like this:

return {
  myProperty: "hello world"
};

with the { on the same line as return.

Pointy
  • 405,095
  • 59
  • 585
  • 614