In Javascript, we can call methods on string literals directly without enclosing it within round brackets. But not for other types such as numbers, or functions. It is a syntax error, but is there a reason as to why the Javascript lexer needs these other types to be enclosed in round brackets?
For example, if we extend Number, String, and Function with an alert method and try calling this method on the literals, it's a SyntaxError for Number and Function, while it works for a String.
function alertValue() {
alert(this);
}
Number.prototype.alert = alertValue;
String.prototype.alert = alertValue;
Function.prototype.alert = alertValue;
We can call alert directly on a string object:
"someStringLiteral".alert() // alerts someStringLiteral
but it's a SyntaxError on numbers, and functions.
7.alert();
function() {}.alert();
To work with these types, we have to enclose it within brackets:
(7).alert(); // alerts "7"
(function() {}).alert(); // alerts "function() {}"
Update:
The link by @Crescent and answers by @Dav and @Timothy explain why 7.alert()
fails, as it's looking for a numerical constant, and to get past it, insert extra whitespace or an extra dot.
7 .alert()
7..alert()
7. .alert();
Is there a similar syntactical reasons for why functions need to be enclosed in parentheses before invoking a method on them?
I am not well versed with interpreters and lexers to know if it's a problem that can be solved with some sort of a lookahead, as Ruby is a dynamic language and takes care of this problem. For example:-
7.times { |i| print i }
Update 2:
@CMS's answer has been spot on in understanding why functions were not working above. The statements below work:
// comma operator forces evaluation of the function
// alerts "function() {}"
<any literal>, function() {}.alert();
// all examples below are forced to be evaluated as an assignment expression
var a = function() {}.alert();
var b = {
x: function() { return "property value" }.alert()
}
[ function() { return "array element" }.alert() ];