es6 修饰器

写在前面,因为function存在变量提升,所以修饰器是只能修饰类,而不能修饰函数

  • 修饰器是一个函数,用来修改类的行为或属性
function testable(target) {
  target.isTestable = true;
  //也可以修改类的原型,
  target.prototype.isTestable = true
}
@testable
class MyTestableClass {}
// 上面的这一句等同于 MyTestableClass = testable(MyTestableClass)
console.log(MyTestableClass.isTestable) // true

翻译过来,其实它是这样的

@decorator
class A {}
// 等同于
class A {}
A = decorator(A) || A;

所以可以看出修饰器其实就是一些函数,用来修改类的行为(原型,静态属性...都可以),只不过这些行为可能有公共性,所以就写一个方法去改变,然后取了一个装逼的名字叫修饰器

  • 既然修饰器是一个函数,那么参数肯定少不了
function testable(isTestable) {
      return function(target) {
              target.isTestable = isTestable;
       }
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
@testable(false)
class MyClass {}
MyClass.isTestable // false

有点绕啊... 慢慢来

testable(true)
//相当于返回一个函数,我们用个变量接收一下
let resultFunc = testable(true)
//就相当于
let resultFunc = function(target){
      target.isTestable = true
}
//现在继续修饰
@resultFunc
class MyTestableClass{}
//等同于原来的
@testable(true)
class MyTestableClass{}
// 是不是OK了,要是需要多个参数,那就再最外面的函数中多传就行

再来看一个列子,巩固一下

function mixins(...list) {
      return function (target) {
        // 其实直接在外面使用这一句话就好,非要装逼搞个修饰器的概念,好吧...,我承认是因为站的立场不同,我是使用者的立场,他们是规范的立场
         Object.assign(target.prototype, ...list)
       }
}
const Foo = {
       foo() { console.log('foo') }
};
@mixins(Foo)
class MyClass {}
let obj = new MyClass();
obj.foo() // 'foo'
  • 修饰类的属性
class Person {
       @readonly
       name() { return `${this.first} ${this.last}` }
}
function readonly(target, name, descriptor){
          // descriptor对象原来的值如下
          // {
          //   value: specifiedFunction,
          //   enumerable: false,
          //   configurable: true,
          //   writable: true
          // };
          descriptor.writable = false;
          return descriptor;
}
readonly(Person.prototype, 'name', descriptor);
// 类似于
Object.defineProperty(Person.prototype, 'name', descriptor);

很难理解是吗,通过控制台输出,我们发现target其实是当前类(因为现在是在类里面使用)的原型,name就是下面的属性名,descriptor就是这个属性的描述,修饰器修改的其实就是这个描述,不知道描述是什么..请自行查阅资料,再来看一个例子

class Math {
     @log
     add(a, b) {
       return a + b;
     }
}
function log(target, name, descriptor) {
     var oldValue = descriptor.value;
     // 打印出来发现,oldValue其实就是function add(){}
     descriptor.value = function() {
       console.log(`Calling "${name}" with`, arguments);
       return oldValue.apply(null, arguments);
     };
     return descriptor;
}
const math = new Math();
// passed parameters should get logged now
math.add(2, 4);
  • 若是同一个方法有多个修饰器,会从外向内进入,然后由内向外执行(简单理解就是把内部执行的结果当做参数传向外面的)
function dec(id){
    console.log('evaluated', id);
    return (target, property, descriptor) => console.log('executed', id);
}
class Example {
    @dec(1)
    @dec(2)
    method(){}
}
// evaluated 1
// evaluated 2
// executed 2
// executed 1
  • babel的支持性,需要安装babel-plugin-transform-decorators插件,然后配置.babelrc,
npm install babel-core babel-plugin-transform-decorators
// .babelrc
{
  "plugins": ["transform-decorators"]
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,993评论 19 139
  • (a fork of Airbnb's Javascript Style Guide) Strikingly ES...
    飘零_zyw阅读 1,200评论 1 2
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,789评论 0 9
  • “儿子,在某个意义上,你就是我,我就是你” “霍元甲幼时也与你一样,都是早产的孩子,他的父亲怜惜儿子,认为霍元甲...
    燕莱春灵阅读 440评论 0 1
  • 前世的千百次回眸, 才换来今生的相视一笑! 我们还能不能再见面, 我在佛前苦苦求了几千年! 人缘佛缘心缘情缘, 万...
    画心心语阅读 459评论 3 14