Uncaught SyntaxError: Setter must have exactly one formal parameter

自作多情 提交于 2019-12-22 05:55:21

问题


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


回答1:


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"



回答2:


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.)




回答3:


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



来源:https://stackoverflow.com/questions/33815053/uncaught-syntaxerror-setter-must-have-exactly-one-formal-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!