js几个常用知识

这里只列举了几个常用的

  1. 最优化的继承方式: 圣杯模式

        var inherit = (function(c, p) {
            var F = function(){};
            return function(c,p) {
                F.prototype = p.prototype;
                c.prototype = new F();
                c.uber = p.prototype;
                c.prototype.constructor = c;
            }
        })();
    
  2. 类型判断
    基本类型(null) 使用String(null) 返回’null’
    基本类型(string/number/boolean/undefined) 以及 function 使用typeof
    其余引用类型(Array/Date/RegExp/Error/Object) 调用toString后根据[object xxx]进行判断

    var class2Type = {}
    'Array Date RegExp Object Error'.split(' ').forEach(e => class2Type['[object ' + e + ']'] = e.toLowerCase())
    function type(obj) {
        if(obj == null) return String(obj)
        return typeof obj === 'object' ? class2Type[Object.prototype.toString.call(obj)] || 'object' : typeof obj
    }
    
  3. 防抖和节流
    防抖:将多次高频操作优化为只在最后一次执行

    function debounce(fn, wait, immediate) {
        let timer = null
        
        return function() {
            let args = arguments
            let context = this
            
            // 初始立即执行
            if (immediate && !timer) {
                fn.apply(context, args)
            } 
            
            if(timer) clearTimeout(timer)
            
            timer = setTimeout(function() {
                fn.apply(context, args)
            }, wait)
        }
    }

节流:每隔一段时间执行一次

 function throttle(fn, wait, immediate) {
     let timer = null
     let callNow = immediate
     
     return function() {
         let context = this,
         args = arguments
         
         // 是否立即执行
         if (callNow) {
             fn.apply(context, args)
             callNow = false
         }
         
         // 每隔一段时间执行
         if (!timer) {
             timer = setTimeout(function() {
                 fn.apply(context, args)
                 timer = null
             }, wait)
         }
     }
 }
  1. 函数柯里化
    在一个函数中,首先填充几个函数,然后再返回一个新的函数的技术,称为函数的柯里化。
    通常用于在不侵入函数的前提下,为函数 预置通用函数, 供多次重复使用。
    const add = function add(x) {
        return function(y) {
            return x + y
        }
    }
    
    // 通用初始函数
    const add1 = add(1)
    
    add1(2) === 3
    add1(20) === 21
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值