为何个人装饰器没别人的强?

装饰器(Decorator)是一种设计模式,容许向一个对象添加功能,可是又不改变其内部结构。装饰器只是ES7中提案,目前处于Stage 2阶段,可是不久的未来就会变成规范。它主要用来修饰类以及类属性。前端

本文总共分为五个部分:react

  • 修饰类
  • 修饰类属性
  • 三个参数
  • 在React的应用
  • Babel编译

修饰类

@isPerson
class Person {}

function isPerson(target) {
  target.prototype.isPerson = true;
}

const person1 = new Person();
console.log(person1.isPerson); // true
复制代码

上面有一个Person类,咱们写了一个isPerson装饰器修饰它,最终咱们实例化Person时,实例上多了isPerson属性。git

@isPerson(true)
class Person {}

function isPerson(bol) {
  return function(target) {
    target.prototype.isPerson = true;
  }
}
复制代码

一样咱们也能够给装饰器isPerson添加参数,而装饰器内容就会多一层结构,return对一个对象。因此装饰器是支持传参和不传参的。es6

本质上能够把Person看做一个方法,而实际上装饰器就是将方法当参数传入。在Babel编译我会讲解装饰器的本质。github

isPerson(true)(function Person() {})
复制代码

修饰类属性

class Person {
  firstName = 'Peter';
  lastName = 'Cheng';

  @readonly
  realName() { return `${this.firstName} ${this.lastName}` };
}

function readonly(target, name, descriptor) {
  descriptor.writable = false;
}

const person2 = new Person();
console.log(person2.realName = 1);
复制代码

同时给类PersonrealName方法添加了readonly装饰器,当输出实例的realName属性时,程序会报错,Uncaught TypeError: Cannot assign to read only property 'realName' of object '#<Person>'。注意,这里实际上修饰的是类方法,装饰器目前不能修饰类里面的变量,好比firstNamelastName设计模式

三个参数

  • target

若是修饰类,那target就是目标自己,第一个例子中就是Person类。若是你修饰的是类方法,那target就是类实例。数组

  • name

类名或者类方法名称,一样第一个例子,打印出来就是Personbash

  • descriptor

属性的描述对象。它具备以下几个属性,valueenumerableconfigurablewritable。value是修饰对象自己,而其余值和Object.defineProperty的属性同样,控制值的行为。babel

{
   value: ƒ realName(),
   enumerable: false,
   configurable: true,
   writable: false
 };
复制代码

在React的应用

装饰器在React中的应用咱们随处看见,好比Redux,自定义HOC等,其实这些都是高阶函数的应用。app

下面咱们实现一个打点装饰器,当咱们触发postClick方法时,会输出一个打点的log,最终会输出postClick 2。咱们经过拦截value,并重写value,将参数id打印了出来。

class App extends Component {
  @analytic()
  postClick(id = 1) {}
}

function analytic(args) {
  return function decorator(target, name, descriptor) {
    if (typeof descriptor === 'undefined') {
      throw new Error('@analytic decorator can only be applied to class methods');
    }

    const value = descriptor.value;
    function newValue(...args) {
      console.log(`${name} ${args}`);
      return value.bind(this)(args);
    };

    
    return {
      ...descriptor,
      value: newValue
    };
  }
}

const app = new App();
app.postClick(2);
复制代码

Babel编译

咱们选择修饰类方法的例子,看一下最简单的装饰器若是编译成ES5代码会是怎么样。能够用Babel官方的网址 babeljs.io/repl,看一下第一个例子中代码被编译成什么样子。

class Person {
  firstName = 'Peter';
  lastName = 'Cheng';

  @readonly
  realName() { return `${this.firstName} ${this.lastName}` };
}

function readonly(target, name, descriptor) {
  descriptor.writable = false;
}

const person2 = new Person();
console.log(person2.realName = 1);
复制代码

编译以后

function _decorate(decorators, factory, superClass, mixins) {}

// 省略中间一大推

var Person = _decorate(null, function (_initialize) {
  var Person = function Person() {
    _classCallCheck(this, Person);

    _initialize(this);
  };

  return {
    F: Person,
    d: [{
      kind: "field",
      key: "firstName",
      value: function value() {
        return 'Peter';
      }
    }, {
      kind: "field",
      key: "lastName",
      value: function value() {
        return 'Cheng';
      }
    }, {
      kind: "method",
      decorators: [readonly],
      key: "realName",
      value: function realName() {
        return "".concat(this.firstName, " ").concat(this.lastName);
      }
    }]
  };
});

function readonly(target, name, descriptor) {
  descriptor.writable = false;
}

var person2 = new Person();
console.log(person2.realName = 1);
复制代码

其实主要看Person对象有那些变化,Babel将类编译成了ES5的function,而且外面套一层装饰器,可是装饰器最终仍是赋值给Person变量。内部Person对象最终返回一个对象,而key为realName的对象有一个decorators,它是一个数组。咱们看看decorators作了什么。其实就是遍历数组,将参数最终映射到Object.defineProperty,操做对象的可写入等属性。

结束语

经过本文咱们知道了装饰器是什么,而且用来作什么,以及实质是什么。最近看了一部电影《斯隆女士》,里面就有一个片断阐述专业性的重要性,做为前端,首先须要掌握的就是ES相关的知识。终于整理完装饰器的知识了,我最近正在用Node + Flutter作一个App,最终计划是发布上线,敬请期待。

我用create-react-app生成了一个项目,能够直接使用装饰器。github.com/carrollcai/…

参考:

es6.ruanyifeng.com/#docs/decor…


写做时间: 20190922

相关文章
相关标签/搜索