前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ES6装饰器Decorator的实现原理

ES6装饰器Decorator的实现原理

原创
作者头像
伯爵
修改2019-10-11 10:14:00
2K0
修改2019-10-11 10:14:00
举报
文章被收录于专栏:前端小菜鸟前端小菜鸟

NOTE Decorators are an experimental feature that may change in future releases.

装饰器是类的一种附加功能,支持注释或修改类和类成员。目前处于ES6提案的第二阶段(Stage 2),可以借助babel等工具使用该实验性的特性。

Decorator

使用@ 操作符将装饰器添加到类或者类的方法作为修饰。

代码语言:txt
复制
// 1.修饰类
function runBoolFun(target) {
    target.runBool= true;
    return target;
}

@runBoolFun
class Person{}
console.log(Person.runBool)

// 2.修饰属性
function readonly(target, name, descriptor) {
    discriptor.writable = false;
    return discriptor;
}

class Person{
    @readonly
    run() {
        console.log("跑的不是很快!");
    }
}

let person = new Person();
person.say = run() {
    console.log("跑的很快!");
}

person.run() // 跑的不是很快!

JavaScript没有类的概念,我们的class字符其实是JavaScript实现的一种语法糖,定义Person的类:

代码语言:txt
复制
class Person{
    say() {
        return `Hello!`
    }
}

这个简单的Person类只包含一个say()方法,我们实现一个定义类的语法糖的核心原理:

代码语言:txt
复制
function Person() {}
Person.defineProperty(Person.prototype, 'say', {
    value: function() {return `Hello!`},
    enumerable: false,
    configurable: true,
    writable: true
})

这是我们熟悉的ES5的用法,我们重新复习一下Object.defineProperty的方法。

代码语言:txt
复制
Object.defineProperty(obj, prop, descriptor)

接受三个不同的参数:

  • obj:要定义属性的对象
  • prop:要定义或者修改的属性或者符号
  • descriptor:定于或者修改描述符

我们可以通过修改或者定义描述符修改对象属性的值,当我们使用装饰器修饰对象属性的过程,其实是执行下面的一段过程:

代码语言:txt
复制
let descriptor = {
    value: function() {
        console.log("hello");
    },
    enumerable: false,
    configurable: true,
    writable: true
};
descriptor = readonly(Person.prototype, "say", descriptor) || descriptor;
Object.defineProperty(Person.prototype, "say", descriptor);

我们知道装饰器也是ES6提供的一个语法糖,当我们使用装饰器修饰类的时候,装饰器runBoolFun是一个纯粹的函数,类本身也是一个函数,target指向的是这个函数(类),执行过程如下:

代码语言:txt
复制
Person = runBoolFun(function Person() { })
参考

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Decorator
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档