John Page
John Page

Reputation: 363

Why is this Javascript syntax illegal?

Both Chrome and Safari report this is illegal. They report "unexpected token 'this'" pointing at the 'this.b'. Here is the minimum code needed to show the problem:

function x(){ this.a = function() {} this.b = function() {}  }

It only happens if the two declarations are on the same line. Any ideas? Looks legal to me.
It's annoying because this is what comes out of a Javascript minifier.

Upvotes: 2

Views: 112

Answers (2)

Quentin
Quentin

Reputation: 943518

There is no semi-colon terminating the first statement inside the function x.

Semi-colon insertion only works at new lines.

// Valid but nasty
this.a = function() {}
this.b = function() {}

// Valid
this.a = function() {};
this.b = function() {};

// Valid
this.a = function() {}; this.b = function() {};

Upvotes: 0

Daniel Williams
Daniel Williams

Reputation: 8885

Javascript will automatically insert semi-colons on new lines. What is missing here are the original semi-colons to delimit the end of your statement.

Insert semicolons after your closing braces like proper JS and it will work fine.

Upvotes: 2

Related Questions