10

In JavaScript it is possible to do:

var a = {this: this}

but with ES6 property shorthand I get SyntaxError:

var b = {this}; // SyntaxError: this is a reserved identifier

This is not a real use case but I am just wondering what is the difference between these two. I thought it should do the same (either create a new object or throw an error).

UPDATE:

I run this example in Firefox 42.0. However it works in babel-node (it creates object { this: {} } without error). So what's the correct behavior?

madox2
  • 49,493
  • 17
  • 99
  • 99

1 Answers1

8

The grammar for that shorthand property initializer clause stipulates that the single term used must be an Identifier. Because this is a reserved word, it isn't an identifier, so you get a syntax error.

The relevant part of the spec is section 12.2.6.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    For what it's worth I agree that the fact that you *can* use `this` as a property name but the attempt in the OP fails constitutes a language wart, but you kind-of get used to those as a JavaScript programmer. – Pointy Dec 25 '15 at 23:29
  • I'm confused about this. First, `{ this }` works for me at least in babel-node. Babel compiles it into `{ "this": this };`, which is perfectly legal. I understand that `{ break }` could not work, even through `break` is allowed as a key, because there can be no identifier `break`. But `this` is a kind of special identifier, sorry if I don't have the terminology exactly right. So, is this a language wart, or is Babel allowing it when it shouldn't, or is whatever engine/processor the OP is using not allowing it when it should? –  Dec 26 '15 at 05:26