概述
1.类的修饰:
修饰器(Decorator)函数,用来修改类的行为。
修饰器是一个对类进行处理的函数。修饰器函数的第一个参数,就是所要修饰的目标类。
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
}
MyTestableClass.isTestable
上面代码中,@testable
就是一个修饰器。它修改了MyTestableClass
这个类的行为,为它加上了静态属性isTestable
。testable
函数的参数target
是MyTestableClass
类本身。参数target
,就是会被修饰的类。
如果觉得一个参数不够用,可以在修饰器外面再封装一层函数。
function testable(isTestable) {
return function(target) {
target.isTestable = isTestable;
}
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
@testable(false)
class MyClass {}
MyClass.isTestable // false
注意,修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码。也就是说,修饰器本质就是编译时执行的函数。
前面的例子是为类添加一个静态属性,如果想添加实例属性,可以通过目标类的prototype
对象操作。
function testable(target) {
target.prototype.isTestable = true;
}
@testable
class MyTestableClass {}
let obj = new MyTestableClass();
obj.isTestable // true
上面代码中,修饰器函数testable
是在目标类的prototype
对象上添加属性,因此就可以在实例上调用。
实际开发中,React 与 Redux 库结合使用时,常常需要写成下面这样。
class MyReactComponent extends React.Component {}
export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);
有了装饰器,就可以改写上面的代码。
@connect(mapStateToProps, mapDispatchToProps)
export default class MyReactComponent extends React.Component {}
2.方法的修饰:
修饰器不仅可以修饰类,还可以修饰类的属性。
function readonly(target, name, descriptor) {
// descriptor对象原来的值如下
// {
// value: specifiedFunction, //该属性对应的值
// enumerable: false,// 为true时,才能够出现在对象的枚举属性中
// configurable: true,// 为true时,该属性描述符才能够被改变
// writable: true // 为true时,value才能被赋值运算符改变
// };
descriptor.writable = false
return descriptor
}
class Person {
@readonly
say () {
console.log("hellow!!")
}
}
let p = new Person()
p.say = function () {
console.log("你好!")
}
// 由于设置了writable=false,所以不允许修改
p.say() // hellow!!
上面代码中,修饰器readonly
用来修饰“类”的name
方法。
修饰器函数readonly
一共可以接受三个参数。
readonly(Person.prototype, 'say', descriptor);
// 类似于
Object.defineProperty(Person.prototype, 'say', descriptor);
修饰器第一个参数是类的原型对象,上例是Person.prototype
,修饰器的本意是要“修饰”类的实例,但是这个时候实例还没生成,所以只能去修饰原型(这不同于类的修饰,那种情况时target
参数指的是类本身);第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象。
另外,上面代码说明,修饰器(readonly)会修改属性的描述对象(descriptor),然后被修改的描述对象再用来定义属性。
修饰器传参(用法同类的修饰器,可以在修饰器外面再封装一层函数):
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
如果同一个方法有多个修饰器,会像剥洋葱一样,先从外到内进入,然后由内向外执行。上面代码中,外层修饰器@dec(1)
先进入,但是内层修饰器@dec(2)
先执行。
修饰器只能用于类和类的方法,不能用于函数,因为存在函数提升(如果一定要修饰函数,可以采用高阶函数的形式直接执行。)
借鉴阮一峰的Es6教程:http://es6.ruanyifeng.com/#docs/decorator
最后
以上就是稳重苗条为你收集整理的es6 Decorator修饰器的全部内容,希望文章能够帮你解决es6 Decorator修饰器所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复