getter-return (Rules) – Eslint 中文开发手册

[
  •   Eslint 中文开发手册

    getter-return (Rules) - Eslint 中文开发手册

    get 语法将一个对象属性绑定到一个函数,该函数将在查找该属性时被调用。它首先在 ECMAScript 5 中引入:

    var p = {
            get name(){
                return "nicholas";
            }
        };
    
        Object.defineProperty(p, "age", {
            get: function (){
                return 17;
            }
        });

    请注意,每个getter预期都会返回一个值。

    规则细节

    该规则强制在属性获取器中存在返回语句。

    此规则的错误代码示例:

    /*eslint getter-return: "error"*/
    
    p = {
        get name(){
            // no returns.
        }
    };
    
    Object.defineProperty(p, "age", {
        get: function (){
            // no returns.
        }
    });
    
    class P{
        get name(){
            // no returns.
        }
    }

    此规则的正确代码示例:

    /*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(默认)不允许隐式返回未定义的返回; 声明。

    选项的正确代码示例{ "allowImplicit": true }:

    /*eslint getter-return: ["error", { allowImplicit: true }]*/
    p = {
        get name(){
            return; // return undefined implicitly.
        }
    };

    何时不使用它

    如果您的项目不使用 ES5 属性获取器,则不需要此规则。

    进一步阅读

    MDN: Functions getterUnderstanding ES6: Accessor Properties

    版本

    这条规则是在 ESLint 4.2.0 中引入的。

    资源

    Rule sourceDocumentation source

  •   Eslint 中文开发手册
    ]
    转载请保留页面地址:https://www.breakyizhan.com/javascript/34150.html
    原文地址:https://www.cnblogs.com/breakyizhan/p/13286272.html