What is a decorator in es6
In es6, decorator (Decorator) is a syntax related to a class (class), used to annotate or modify classes and class methods; the decorator is actually a function executed at compile time, the syntax " @functionname", usually placed before the definition of classes and class methods. There are two types of decorators: class decorators and class method decorators.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
The Decorator Pattern allows adding new functionality to an existing object without changing its structure. This type of design pattern is a structural pattern, which acts as a wrapper around an existing class.
This mode creates a decoration class to wrap the original class and provide additional functionality while maintaining the integrity of the class method signature.
ES6 Decorator
In ES6, decorator (Decorator) is a class-related syntax used to annotate or modify classes and class methods.
A decorator is actually a function, usually placed in front of classes and class methods.
The decorator changes the behavior of the class when the code is compiled, not at runtime; the essence of the decorator is the function executed during compilation
Decorators can be used to decorate Entire class
@decorateClass class Example { @decorateMethods method(){} }
在上面的代码中使用了两个装饰器,其中 @decorateClass()
装饰器用在类本身,用于增加或修改类的功能;@decorateMethods()
装饰器用在类的方法,用于注释或修改类方法。
两种类型装饰器
装饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。
装饰器只能用于类和类的方法,下面我们分别看下两种类型的装饰器的使用
1、类装饰器
类装饰器用来装饰整个类
类装饰器的参数
target: 类本身,也相当于是 类的构造函数:Class.prototype.constructor。
@decorateClass class Example { //... } function decorateClass(target) { target.isTestClass = true }
如上面代码中,装饰器 @decorateClass 修改了 Example 整个类的行为,为 Example 类添加了静态属性 isTestClass。装饰器就是一个函数,decorateClass 函数中的参数 target 就是 Example 类本身,也相当于是类的构造函数 Example.prototype.constructor.
装饰器传参
上面实现的装饰器在使用时是不能传入参数的,如果想要在使用装饰器是传入参数,可以在装饰器外面再封装一层函数
@decorateClass(true) class Example { //... } function decorateClass(isTestClass) { return function(target) { target.isTestClass = isTestClass } }
上面代码中实现的装饰器在使用时可以传递参数,这样就可以根据不同的场景来修改装饰器的行为。
实际开发中,React 与 Redux 库结合使用时,常常需要写成下面这样。
class MyReactComponent extends React.Component {} export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);
有了装饰器,就可以改写上面的代码。
@connect(mapStateToProps, mapDispatchToProps) export default class MyReactComponent extends React.Component {}
2、类方法装饰器
类方法装饰器用来装饰类的方法
类方法装饰器的参数
target:
装饰器修饰的类方法是静态方法:target 为类的构造函数
装饰器修饰的类方法是实例方法:target 为类的原型对象
method:被修饰的类方法的名称
descriptor:被修饰成员的属性描述符
// descriptor对象原来的值如下 { value: specifiedFunction, enumerable: false, configurable: true, writable: true };
class Example { @log instanceMethod() { } @log static staticMethod() { } } function log(target, methodName, descriptor) { const oldValue = descriptor.value; descriptor.value = function() { console.log(`Calling ${name} with`, arguments); return oldValue.apply(this, arguments); }; return descriptor; }
如上面代码中,装饰器 @log 分别装饰了实例方法 instanceMethod 和 静态方法 staticMethod。@log 装饰器的作用是在执行原始的操作之前,执行 console.log 来输出日志。
类方法装饰器传参
上面实现的装饰器在使用时是不能传入参数的,如果想要在使用装饰器是传入参数,可以在装饰器外面再封装一层函数
class Example { @log(1) instanceMethod() { } @log(2) static staticMethod() { } } function log(id) { return (target, methodName, descriptor) => { const oldValue = descriptor.value; descriptor.value = function() { console.log(`Calling ${name} with`, arguments, `this id is ${id}`); return oldValue.apply(this, arguments); }; return descriptor; } }
上面代码中实现的装饰器在使用时可以传递参数,这样就可以根据不同的场景来修改装饰器的行为。
类装饰器与类方法装饰器的执行顺序
如果在一个类中,同时使用装饰器修饰类和类的方法,那么装饰器的执行顺序是:先执行类方法的装饰器,再执行类装饰器。
如果同一个类或同一个类方法有多个装饰器,会像剥洋葱一样,先从外到内进入,然后由内到外执行。
// 类装饰器 function decoratorClass(id){ console.log('decoratorClass evaluated', id); return (target) => { // target 类的构造函数 console.log('target 类的构造函数:',target) console.log('decoratorClass executed', id); } } // 方法装饰器 function decoratorMethods(id){ console.log('decoratorMethods evaluated', id); return (target, property, descriptor) => { // target 代表 // process.nextTick((() => { target.abc = 123 console.log('method target',target) // })) console.log('decoratorMethods executed', id); } } @decoratorClass(1) @decoratorClass(2) class Example { @decoratorMethods(1) @decoratorMethods(2) method(){} } /** 输入日志 **/ // decoratorMethods evaluated 1 // decoratorMethods evaluated 2 // method target Example { abc: 123 } // decoratorMethods executed 2 // method target Example { abc: 123 } // decoratorMethods executed 1 // decoratorClass evaluated 1 // decoratorClass evaluated 2 // target 类的构造函数: [Function: Example] // decoratorClass executed 2 // target 类的构造函数: [Function: Example] // decoratorClass executed 1
如上面代码中,会先执行类方法的装饰器 @decoratorMethods(1) 和 @decoratorMethods(2),执行完后再执行类装饰器 @decoratorClass(1) 和 @decoratorClass(2)
上面代码中的类方法装饰器中,外层装饰器 @decoratorMethods(1) 先进入,但是内层装饰器 @decoratorMethods(2) 先执行。类装饰器同理。
利用装饰器实现AOP切面编程
function log(target, name, descriptor) { var oldValue = descriptor.value; descriptor.value = function () { console.log(`Calling "${name}" with`, arguments); return oldValue.apply(null, arguments); } return descriptor; } // 日志应用 class Maths { @log add(a, b) { return a + b; } } const math = new Maths(); // passed parameters should get logged now math.add(2, 4);
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of What is a decorator in es6. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

How do decorators and context managers work in Python? In Python, decorators and context managers are two very useful concepts and features. They are all designed to simplify code, increase code readability, and facilitate code reuse. 1. Decorator A decorator is a special function in Python that is used to modify the behavior of a function. It allows us to wrap or extend the original function without modifying it. Decorators are widely used in many Python frameworks and libraries, such as Flask, Dj

This is our third article to teach you step by step how to implement a Python timer. The first two articles: teach you step by step how to implement a Python timer, and use context managers to extend Python timers, making our Timer class convenient to use, beautiful and practical. But we are not satisfied with this, there is still a use case that can simplify it further. Suppose we need to track the time spent in a given function in our code base. With a context manager, you basically have two different options: 1. Use Timer every time you call a function: with Timer("some_name"): do_something() When we are in

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.
