Benjamin Crouzier
Benjamin Crouzier

Reputation: 41865

Can you overload the operator new in javascript ? What will it do?

I am trying to make a website work on ie8.

I have found the following js code:

var autocompleteAddressController=(function(){
  var my={};
  //...

  my.new=function(val){
    //...
  };
});

And in another file:

var address = autocompleteAddressController.new("#user_address_name"); 

//...

This works fine in recent browsers (chrome and safari)

But it breaks on ie8. I am guessing the the javascript parser of ie8 does not support that we use the reserved name "new" for our custom functions, so in the console I have the error: expected identifier on those expressions: my.new=function and autocompleteAddressController.new.

Upvotes: 0

Views: 977

Answers (1)

James Allardice
James Allardice

Reputation: 165961

Will it override the new operator

No. You cannot override operators in JavaScript.

All the code does is create a method of my which happens to have the identifier new. This is valid in all environments, but it is only valid to use a reserved word as a property identifier via dot-notation in ES5. You can make it work in IE8 and other non-ES5 environments by using square brackets:

my["new"] = function (val) { /*...*/ }

// And in your other file...

var address = autocompleteAddressController["new"]("#user_address_name");

Update

To slightly expand upon this, here are the relevant sections of the ES5 grammar. First, here's the Identifier production:

Identifier ::
    IdentifierName but not ReservedWord

Notice that an identifer cannot be a reserved word (new is a reserved word). The IdentifierName production simply specifies the characters that are allowed in an identifier (with no restrictions based on reserved words).

Here's the grammar for properties in "object initialisers" (object literals):

PropertyName :
    IdentifierName
    StringLiteral
    NumericLiteral

Notice that it refers to IdentifierName, rather than Identifier. This is the production that allows the use of reserved words as property identifiers.

Finally, compare that production to the one found in the older ES3 spec:

PropertyName :
    Identifier
    StringLiteral
    NumericLiteral

This time, it uses Identifier, and not IdentifierName. Since the Identifier production disallows the use of reserved words, the code is invalid in ES3 environments.

Upvotes: 6

Related Questions