Dinna
Dinna

Reputation: 85

Uncaught SyntaxError: Setter must have exactly one formal parameter

I'm trying to understand getters and setters on JS and I can't seem to get pass this error. Can anyone provide any insight as to why I'm getting this error?

var book = {
    year: 2004,
    edition:1,
    get newYear(){
        return "Hello, it's " + this.year;
    },
    set newYear(y, e){
        this.year = y;
        this.edition = e;
    }
};

Uncaught SyntaxError: Setter must have exactly one formal parameter

Upvotes: 8

Views: 17786

Answers (4)

Hasnain Sikander
Hasnain Sikander

Reputation: 511

Well, all the above answers are all good and work fine. In spite of all these, you can simply specify one setter for setting one value and another for setting another value. Like this:

var book = {
    year: 2004,
    edition: 1,
    get newYear() {
        return "Hello, it's " + this.year;
    },
    set newYear(y) {
        this.year = y;
    },
    set newEdition(e) {
        this.edition = e
    }

};
book.newYear = 3232
book.edition = 3
console.log(book)

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

The setter function is called when you assign the value that setter represent:

var obj = {
  set a(newVal) { console.log("hello"); }
}
obj.a = 1; // will console log "hello"

As you can see it doesn't make sense for a setter to take multiply arguments, but it gives you the freedom to manipulate the value before it is set:

var person = {
  surname: "John",
  lastname: "Doe",
  get fullname() {
    return this.surname + " " + this.lastname;
  },
  set fullname(fullname) {
    fullname = fullname.split(' ');
    this.surname = fullname[0];
    this.lastname = fullname[1];
  }
};

console.log(person.fullname); // "John Doe"
person.fullname = "Jane Roe";
console.log(person.surname); // "Jane"
console.log(person.lastname); // "Roe"

Upvotes: 9

Mike Murphy
Mike Murphy

Reputation: 1046

Try setNewYear and not set newYear and the same for getNewYear not get newYear.

Upvotes: 0

Pointy
Pointy

Reputation: 413757

A setter function is a function that's called implicitly when you do something like:

someObject.property = 25;

Because an assignment operation involves assigning one and only one value, a setter function must have a single argument. It will only ever be called (via the implicit assignment mechanism) with one argument anyway, so a two-argument setter makes little sense.

In your case, you could make your setter take a single object and get the two values out of it:

var book = {
    year: 2004,
    edition:1,
    get newYear(){
        return "Hello, it's " + this.year;
    },
    set newYear(value){
        this.year = value.y;
        this.edition = value.e;
    }
};

Then you can say

book.newYear = { y: 2005, e: 2 };

(Personally I think I'd prefer to do that with destructuring assignment, but it would work.)

Upvotes: 7

Related Questions