0

I'm having a strange issue when defining a method named get or set inside a class. For example, I am defining the class Mem as follows:

class Mem {
    constructor() {
        this.list=[]
    }

    get(index) {
        return this.list[index];
    }

    set(index, value) {
        this.list[index] = value;
    }
}

But I get a SyntaxError: Unexpected token '('

However, when I change the method name to geta or seta, the class definition works and I don't get the SyntaxError.

class Mem {
    constructor() {
        this.list=[]
    }

    geta(index) {
        return this.list[index];
    }

    seta(index, value) {
        this.list[index] = value;
    }
}

I checked that get and set were not restricted keywords in Javascript, so I am confused as to what I am doing wrong.

Nonemoticoner
  • 650
  • 5
  • 14
dqiu
  • 470
  • 2
  • 7
  • 1
    Sounds like an error with whatever environment you're running it through. Copying and pasting your code in Chrome works fine. – Mike Cluck Mar 24 '16 at 23:00
  • Just checked and it works on Chrome. It seems that this error only comes up on Safari. – dqiu Mar 24 '16 at 23:04
  • 2
    You're rushing using ES6 technologies (`class`) on browsers that still don't *fully* support it. Please refer always to the compatibility table. – Roko C. Buljan Mar 24 '16 at 23:07
  • Does it work if you use `["get"]` instead of `get`? – Oriol Mar 24 '16 at 23:09

1 Answers1

0

You are colliding with the getter and setter syntax.

{get prop() { ... } }
{get [expression]() { ... } }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392