NOTE Decorators are an experimental feature that may change in future releases.
装饰器是类的一种附加功能,支持注释或修改类和类成员。目前处于ES6提案的第二阶段(Stage 2),可以借助babel等工具使用该实验性的特性。
使用@ 操作符将装饰器添加到类或者类的方法作为修饰。
// 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的类:
class Person{
say() {
return `Hello!`
}
}
这个简单的Person类只包含一个say()方法,我们实现一个定义类的语法糖的核心原理:
function Person() {}
Person.defineProperty(Person.prototype, 'say', {
value: function() {return `Hello!`},
enumerable: false,
configurable: true,
writable: true
})
这是我们熟悉的ES5的用法,我们重新复习一下Object.defineProperty的方法。
Object.defineProperty(obj, prop, descriptor)
接受三个不同的参数:
我们可以通过修改或者定义描述符修改对象属性的值,当我们使用装饰器修饰对象属性的过程,其实是执行下面的一段过程:
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指向的是这个函数(类),执行过程如下:
Person = runBoolFun(function Person() { })
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有