码迷,mamicode.com
首页 > Web开发 > 详细

js应用技巧集合

时间:2020-03-24 12:52:02      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:type   rip   描述符   person   class   来源   例子   mount   nbsp   

目录

  1. 装饰器

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 函数中,一般会接收三个参数:

  1. target:被修饰的类
  2. name:类成员的名字
  3. 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)
            }
        }
    }
}

 

js应用技巧集合

标签:type   rip   描述符   person   class   来源   例子   mount   nbsp   

原文地址:https://www.cnblogs.com/670074760-zsx/p/12557983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!