简体   繁体   English

为什么“setter是在没有getter的情况下定义的”JSHint错误?

[英]Why is “setter is defined without getter” a JSHint error?

Reference jsfiddle 参考jsfiddle

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

JSHint flags this as "setter is defined without getter". JSHint将此标记为“setter is 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. 我所见过的所有JSHint旗帜都有一个合理的解释。 I can't come up with a reason for why this is a bad thing. 我无法想出为什么这是一件坏事。

I don't think JSHint has a good reason to warn about this situation. 我不认为JSHint有充分的理由警告这种情况。 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. 我没有在规范中看到任何内容( http://www.ecma-international.org/publications/standards/Ecma-262.htm ,第30-31页),如果有一个二传手或者需要有吸气剂反之亦然,很容易想象一个不暗示吸气剂的定型器。 For example, you might want to set a dirty flag in a setter. 例如,您可能希望在setter中设置脏标志。 There would be no reason to define a getter. 没有理由定义一个getter。

I did not see a justification in the JSHint source, or its history. 我没有在JSHint来源或其历史中看到任何理由。

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. 这类似于写foo == null时的警告 - 它不是非法的,甚至不一定是错的,但它更可能是错误的,而不是正确的。

You can also have code like this and you'll get the same JSHint error: 你也可以有这样的代码,你会得到相同的JSHint错误:

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: 但是,如果getter和setter具有与下面相同的名称,并且前缀getset在它们之前,则错误将消失:

    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. 对于您的情况,添加与“set”方法同名的get方法,您的错误将消失。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM