table of Contents
1, decorator
/**
Author: sh22n
link: https://juejin.im/post/5e7822c3e51d4526f23a45ae
Source: Nuggets
*/
Class decorator
When decorative, decorator method generally receives a certain type as a parameter. Here is a static property to increase the target class test
examples:
const decoratorClass = (targetClass) => { targetClass.test = '123' } @decoratorClass class Test {} Test.test; // '123'
Higher-order functions using the properties, may also pass parameters to the decorator, the parameters to determine what classes of processing.
const withLanguage = (language) => (targetClass) => { targetClass.prototype.language = language; } @withLanguage('Chinese') class Student { } const student = new Student(); student.language; // 'Chinese'
Class attributes decorator
Class attributes may be used in the decorative properties of the class, method, get/set
function, typically three parameters:
- target : the modified class
- name name of the class members:
- descriptor : attribute descriptor, the object will pass this parameter
Object.defineProperty
Decorative combination
If you want to use multiple decorators, then how to do it? Decorator can be superimposed, are sequentially performed in accordance with the distance from the decorative / attributes to.
class Person {
@time
@log
say() {}
}
Examples: image stabilization and the throttle
const throttle = (time) => { let prev = new Date(); return (target, name, descriptor) => { const func = descriptor.value; if (typeof func === 'function') { descriptor.value = function(...args) { const now = new Date(); if (now - prev > wait) { fn.apply(this, args); prev = new Date(); } } } } } class App extends React.Component { componentDidMount() { window.addEveneListener('scroll', this.scroll); } componentWillUnmount() { window.removeEveneListener('scroll', this.scroll); } @throttle(50) scroll() {} }
const debounce = (time) => { let timer; return (target, name, descriptor) => { const func = descriptor.value; if (typeof func === 'function') { descriptor.value = function(...args) { if(timer) clearTimeout(timer) timer = setTimeout(()=> { fn.apply(this, args) }, wait) } } } }