js应用技巧集合
作者:互联网
目录
1、装饰器
/**
作者:sh22n
链接:https://juejin.im/post/5e7822c3e51d4526f23a45ae
来源:掘金
*/
类装饰器
装饰类的时候,装饰器方法一般会接收一个目标类作为参数。下面是一个给目标类增加静态属性 test
的例子:
const decoratorClass = (targetClass) => { targetClass.test = '123' } @decoratorClass class Test {} Test.test; // '123'
利用高阶函数的属性,还可以给装饰器传参,通过参数来判断对类进行什么处理。
const withLanguage = (language) => (targetClass) => { targetClass.prototype.language = language; } @withLanguage('Chinese') class Student { } const student = new Student(); student.language; // 'Chinese'
类属性装饰器
类属性装饰器可以用在类的属性、方法、get/set
函数中,一般会接收三个参数:
- target:被修饰的类
- name:类成员的名字
- descriptor:属性描述符,对象会将这个参数传给
Object.defineProperty
装饰器组合
如果你想要使用多个装饰器,那么该怎么办呢?装饰器是可以叠加的,根据离被装饰类/属性的距离来依次执行。
class Person { @time @log say() {} }
例子:防抖和节流
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) } } } }
标签:const,技巧,scroll,js,descriptor,集合,targetClass,装饰,属性 来源: https://www.cnblogs.com/670074760-zsx/p/12557983.html