Decorator装饰器(JS)

224 阅读2分钟

对Decorator 的一些介绍

感谢 www.jianshu.com/p/eda05b69c…

前言

  • 许多面向对象都有decorator(装饰器)函数,比如python中也可以用decorator函数来强化代码,decorator相当于一个高阶函数,接收一个函数,返回一个被装饰后的函数。
  • 下面的示例代码,就是用装饰器logDecorator,来将函数进行封装,每次调用时,控制台就会显示被调用的函数名和时间。
import time
            def logDecorator(func):
                def wrapper(*args, **kw):
                    print('%s %s():' % ('调用函数', func.__name__))
                    return func(*args, **kw)
                return wrapper
        @logDecorator
        def now():
            print(time.ctime(time.time()))
        if __name__ == '__main__':
            now()
        

#### 回到JavaScript
  • javascript中也有decorator相关的提案,只是目前node以及各浏览器中均不支持。只能通过安装babel插件来转换代码,插件名叫这个:transform-decorators-legacy
  • 在babel官网的在线试用,安装好transform-decorators-legacy插件,就能看到转义后的代码了,如下
   // 这是源代码
            @testable
            class MyTestableClass {
              // ...
            }

            @testable
            class MyTestableClass2 {
              // ...
            }

            function testable(target) {
              target.isTestable = true;
            }

            MyTestableClass.isTestable // true
  
  • 这是转义后的:
"use strict";

         var _class, _class2;

         function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

         var MyTestableClass = testable(_class = function MyTestableClass() {
           _classCallCheck(this, MyTestableClass);
         }) || _class;

         var MyTestableClass2 = testable(_class2 = function MyTestableClass2() {
           _classCallCheck(this, MyTestableClass2);
         }) || _class2;

         function testable(target) {
           target.isTestable = true;
         }

         MyTestableClass.isTestable; // true
  • 可以从上看出,js中的装饰器就是,调用装饰器函数,对类class进行一层封装。如果装饰器函数有返回值,就取该值赋值给原class,没有返回值就还是取原class。

    装饰类的属性
  • 可以看到python中的装饰器代码,是对一个函数进行装饰,但是在js里却不行。具体原因好像是因为,函数声明的提升。所以只能装饰class,或class的属性。

    function readonly(target, name, descriptor){ descriptor.writable = false; return descriptor; } class Person { @readonly name() { return{this.first}{this.last}} }

  • 如上代码就是对class的name属性进行装饰,此时的decorator函数接收三个参数:类的原型对象、被装饰的属性、被装饰的属性的修饰符对象。然后再根据这些参数进行装饰。

  • decorator装饰属性时,其实不用返回值也可以,然后也支持多个decorator一并使用来装饰同一个属性。

class Person {
              @readonly
              @validate
              name() { return `${this.first} ${this.last}` }
            }

小结

  • 随着es6提出了class的概念之后,在某些场景需要为class或class的属性,进行额外的修饰或注释。decorator的作用就是在此,它是一种对class声明以及class属性的元编程,同时也是注释。