Domanda

Reference jsfiddle

var obj = {
  set bla(k) {
    console.log(k);
  }
};

JSHint flags this as "setter is defined without getter". I am sure there is a way to turn this off, but why is this an error at all? Everything I have seen JSHint flag has had a reasonable explanation. I can't come up with a reason for why this is a bad thing.

È stato utile?

Soluzione

I don't think JSHint has a good reason to warn about this situation. I don't see anything in the specification (http://www.ecma-international.org/publications/standards/Ecma-262.htm, pages 30-31) that requires there to be a getter if there is a setter or vice versa, and it is easy to imagine a setter that doesn't imply a getter. For example, you might want to set a dirty flag in a setter. There would be no reason to define a getter.

I did not see a justification in the JSHint source, or its history.

Altri suggerimenti

This is most likely flagged because it's suspicious. Write-only properties are a fairly unusual thing. The odds that you're doing it on purpose are much lower than the odds that you made a mistake. This is similar to warning when you write foo == null — it isn't illegal or even necessarily wrong, but it's more likely to be wrong than right.

You can also have code like this and you'll get the same JSHint error:

appSession: {
    officername: "Denis Test",
    get getOfficername() {
        return `${this.officername}`;
    },
    set setOfficername(name) {
        this.officername = name;
    }
};

However, if the getter and setter have the same name as below and the prefixes get and set are before them the error will go away:

    get Officername() {
        return `${this.officername}`;
    },
    set Officername(name) {
        this.officername = name;
    }

Notice the difference in how I named my methods in the two examples. For your case, add a get method of the same name as your 'set' method and your error will go away.

var obj = {
    set bla(k) {
        console.log(k);
    }
    get bla(){
        console.log(obj.bla);
    }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top