Ivan Kuckir
Ivan Kuckir

Reputation: 2549

Restriction of "new" keyword in Javascript

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

Answers (4)

Barmar
Barmar

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

Bergi
Bergi

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 Identifiers, 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

georg
georg

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

http://es5.github.io/#x7.6

Upvotes: 3

Roko C. Buljan
Roko C. Buljan

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

Related Questions