开发者

Whitespace before dot (method call) allowed in Javascript?

开发者 https://www.devze.com 2023-02-09 23:55 出处:网络
I want to use the following syntax in Javascript: var bar = foo.replace(/really long regex/, so开发者_开发知识库mething)

I want to use the following syntax in Javascript:

var bar = foo.replace(/really long regex/, so开发者_开发知识库mething)
             .replace(/another really long regex/, something)
             .replace(/yet another really long regex/, something);

since it's (somewhat) more readable than doing this on one line.

Is this allowed? It works fine in Firefox, but I can't find any reference to this syntax anywhere, and I don't want to find out later that there's some obsure browser where this doesn't work.


Yes, Javascript ignores whitespace.

Although if you are going to ignore whitespace you need to be sure and use semicolons to end your expressions. Semicolons are not required, but if they are not used, javascript uses carriage returns to separate commands. Which can cause inconsistent behavior if you're not expecting it.

I have done it many times in my javascript code, since when I'm writing pretty code I don't like to let it go beyond 80 characters.

Take a look at the emcascript standard https://docs.google.com/viewer?url=http%3A%2F%2Fwww.ecma-international.org%2Fpublications%2Ffiles%2FECMA-ST%2FECMA-262.pdf

Line Terminators (which is what your concerned with) are addressed on page 25 of the pdf(page 15 is printed on the sheet). All of section 7 is about formatting, you'll probably find a definition of why it works there(yep I'm lazy and don't want to read the whole section :) ).

Hope that helps!


You can definitely do this but I would be careful. To quote the wikipedia entry - "whitespace in JavaScript source can directly impact semantics". See JavaScript Syntax -Whitespace and Semicolons.


Yes it is I was not able to find any documentation but it is valid. In your case you could loop over the regexps instead

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号