Reputation: 2549
I have this JS code:
var A = {};
A.new = function(n) { return new Array(n); }
It works well in all browsers, but when I try to obfuscate it with obfuscator, it shows an error.
Is it a valid JS code? I looked into specification, but didn't find anything. I know, that browsers sometimes accept syntactically wrong code, but I want to write syntactically correct code.
Note, that I am not doing var new = ...
BTW. what about this?
var a = { "new" : 2 }; // ok?
a.new = 3; // ok?
a["new"] = 3; // ok?
.
EDIT: Thank you all for your help! I wrote an email to obfuscator's authors and they fixed it! :)
Upvotes: 2
Views: 244
Reputation: 781059
Since new
is a reserved word, it can't be used as an identifier, although it can be used as an identifierName. See this section of the ECMAScript specification. So your code is legal, and apparently the obfuscator doesn't understand this distinction.
To work around this, you can access it using array-style notation:
A['new'] = function(n) { return new Array(n); };
Upvotes: 0
Reputation: 664548
Yes, your code is valid an the obfuscator is wrong (or old). new
is a reserved word, that means it is not a valid identifier (e.g. to be used as a variable name). Yet, it is still an IdentifierName
which is valid in object literals and in dot-notation property access.
However, this was not the case in EcmaScript 3, where both of these needed to be Identifier
s, and keywords like new
were invalid. Therefore it is considered bad practise to use these names unquoted in scripts on the web, which might be executed by older browsers.
Upvotes: 3
Reputation: 214969
Reserved words can be used as property identifiers:
A.new = 1
B = { function: 123 }
D.if = { else: 5 }
etc - it's all valid (not necessarily good) javascript.
These things are called "IdentifierName" in the specification, and the only difference between an "IdentifierName" and a regular Identifier is
Identifier :: IdentifierName but not ReservedWord
Upvotes: 3
Reputation: 206121
I see no errors. Lead by a dot its just a property name, just like ['new'], not any more a reserved word.
Upvotes: 0