代码之家  ›  专栏  ›  技术社区  ›  APixel Visuals

JavaScript修饰符的作用是什么?

  •  6
  • APixel Visuals  · 技术社区  · 6 年前

    function myFunction(text) {
      console.log(text)
    }
    

    myFunction() @myFunction @myFunction()

    我觉得我错得很。有人能解释吗?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Bertijn Pauwels    6 年前

    Decorators是用来修饰函数的。

    @time() 就是这样。完成后,可以在要跟踪的每个函数之前使用此装饰器。

    decorator被用作高阶函数,主要是用来对代码进行函数组合!

    一个很好的例子是 @Component()

        2
  •  1
  •   Jared Smith    6 年前

    装潢师可以 . 考虑以下功能:

    function add(a, b) {
      return a + b;
    }
    

    一切都很好。但是假设要添加日志记录:

    function add(a, b) {
      const sum = a + b;
      console.log(a, b, sum);
    }
    

    现在,这个函数变得更长更复杂,并将两个事实上没有任何关系的东西(求和和和日志)合并在一起。更好的方法是:

    function logs(f) {
      return function(...args) {
        const result = f(...args);
        console.log(args, result);
        return result;
      };
    };
    
    const addAndLog = logs(add);
    

    这就是装饰师。您所说的(即JavaScript装饰器建议)只是上述模式的语法捷径。在这里 logs 是一个decorator,它为传入的函数添加了一个功能,即在不必用大量无关代码使函数复杂化的情况下进行日志记录的功能。目前,这个建议仅限于类和方法,但我发现在概念上用普通函数更容易解释。

        3
  •  0
  •   zloctb    5 年前

    function withLoginStatus( DecoratorClass ) {
        return class extends DecoratorClass {
            constructor(...args ) {
                super(...args);
                this.isLoggedIn = false;
            }
    
            setLoggedIn() {
                console.log('setLogin!');
                this.isLoggedIn = true;
            }
        }
    }
    
    
    @withLoginStatus
    class User {
        constructor(firstname, lastName) {
            this.firstname = firstname;
            this.lastName = lastName;
        }
        getFullName() {
            return `${this.firstname} ${this.lastName}`;
        }
    }