标签:type rip 描述符 person class 来源 例子 mount nbsp
目录
/**
作者: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
函数中,一般会接收三个参数:
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) } } } }
标签:type rip 描述符 person class 来源 例子 mount nbsp
原文地址:https://www.cnblogs.com/670074760-zsx/p/12557983.html