js application skill sets

table of Contents

  1. Decorator

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:

  1. target : the modified class
  2. name name of the class members:
  3. 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)
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/670074760-zsx/p/12557983.html