Search code examples
javascriptgetter-setter

Why setter with set keyword and function expressed in ES5 throws syntax error?


Why defining a setter throws syntax error when the function is expressed the ES5 way but works when expressed in ES6.

Setter with ES5 syntax(Doesn't work)

var person = {
  firstName: "John",
  lastName : "Doe",
  language : "",
  set setLanguage: function(val) {
     this.language = val    
  },
  get getLanguage() {
     return this.language   
  }     
}

person.setLanguage = 'EN'
person.getLanguage
`Uncaught SyntaxError: Unexpected token :`

Setter with ES6 syntax (Works)

var person = {
  firstName: "John",
  lastName : "Doe",
  language : "",
  set setLanguage(val) {
     this.language = val    
  },
  get getLanguage() {
     return this.language   
  }     
}

person.setLanguage = 'EN'
person.getLanguage

Thanks


Solution

  • Your second example is not ES6 specific, it's valid ES5 syntax:

    set setLanguage(val) {
        this.language = val;    
    },
    

    From Object Initialiser's specification (ES5)

    PropertyAssignment :
    PropertyName : AssignmentExpression
    get PropertyName ( ) { FunctionBody }
    set PropertyName ( PropertySetParameterList ) { FunctionBody }

    As you can see, there's a : after PropertyName, but there's no : or function in getter or setter

    Update:

    You propably confused concepts of computed property names and getters/setters

    ES6 introduced computed property names, so you can do this (this snippet propably won't work in older browsers, like IE):

    const person = {
      language: "",
      setLanguage(val){
        this.language = val;
      },
      getLanguage(){
        return this.language;
      }
    }
    
    person.setLanguage("EN");
    
    console.log("person.language", person.language);
    console.log("person.getLanguage()",person.getLanguage())

    Note lack of set or get keywords and that you have to call person.setLanguage("EN"); instead of person.setLanguage = "EN";

    In ES5 you'll have to (change const to var and) use:

    setLanguage: function(val) {
        this.language = val;    
    },
    getLanguage: function() {
        return this.language;    
    },