getter-return
在 getter 中执行 return
语句
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
get 语法将对象属性绑定到将在查找该属性时调用的函数。它最初是在 ECMAScript 5 中引入的:
¥The get syntax binds an object property to a function that will be called when that property is looked up. It was first introduced in ECMAScript 5:
var p = {
get name(){
return "nicholas";
}
};
Object.defineProperty(p, "age", {
get: function (){
return 17;
}
});
请注意,每个 getter
都应返回一个值。
¥Note that every getter
is expected to return a value.
规则详情
¥Rule Details
此规则强制在属性 getter 中存在 return 语句。
¥This rule enforces that a return statement is present in property getters.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint getter-return: "error"*/
p = {
get name(){
// no returns.
}
};
Object.defineProperty(p, "age", {
get: function (){
// no returns.
}
});
class P{
get name(){
// no returns.
}
}
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint getter-return: "error"*/
p = {
get name(){
return "nicholas";
}
};
Object.defineProperty(p, "age", {
get: function (){
return 18;
}
});
class P{
get name(){
return "nicholas";
}
}
选项
¥Options
此规则有一个对象选项:
¥This rule has an object option:
-
"allowImplicit": false
(默认)不允许使用return
语句隐式返回undefined
。¥
"allowImplicit": false
(default) disallows implicitly returningundefined
with areturn
statement.
{ "allowImplicit": true }
选项的正确代码示例:
¥Examples of correct code for the { "allowImplicit": true }
option:
/*eslint getter-return: ["error", { allowImplicit: true }]*/
p = {
get name(){
return; // return undefined implicitly.
}
};
何时不使用
¥When Not To Use It
如果你的项目不使用 ES5 属性获取器,则不需要此规则。
¥If your project will not be using ES5 property getters you do not need this rule.
由 TypeScript 处理
使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。
版本
此规则是在 ESLint v4.2.0 中引入。