
getter-return
Enforce return
statements in getters
✅ Recommended
The "extends": "eslint:recommended"
property in a configuration file enables this rule
get 语法将一个对象属性绑定到一个函数上,当该属性被查询时将会被调用。它在 ECMAScript 5 中首次引入。
var p = {
get name(){
return "nicholas";
}
};
Object.defineProperty(p, "age", {
get: function (){
return 17;
}
});
请注意,每个 getter
都应该返回值。
规则细节
这条规则强制要求属性获取器中要有返回语句。
使用此规则的错误示例:
Open in Playground
/*eslint getter-return: "error"*/
p = {
get name(){
// no returns.
}
};
Object.defineProperty(p, "age", {
get: function (){
// no returns.
}
});
class P{
get name(){
// no returns.
}
}
使用此规则的正确示例:
Open in Playground
/*eslint getter-return: "error"*/
p = {
get name(){
return "nicholas";
}
};
Object.defineProperty(p, "age", {
get: function (){
return 18;
}
});
class P{
get name(){
return "nicholas";
}
}
选项
此规则选项为对象:
"allowImplicit": false
(默认值)不允许用return
语句隐式返回undefined
。
使用 { "allowImplicit": true }
选项的正确示例:
Open in Playground
/*eslint getter-return: ["error", { allowImplicit: true }]*/
p = {
get name(){
return; // return undefined implicitly.
}
};
何时不用
如果你的项目不使用 ES5 属性获取器,你就不需要这个规则。
Version
This rule was introduced in ESLint v4.2.0.
Further Reading

