JavaScript 常用函数 通用函数

 

<!DOCTYPE html><html><head><meta charset="utf-8"><title>函数节流 Function throttling</title></head> 
<body>函数节流 Function throttling ......<script>

//函数节流
let throttle= function(fnToBeExecuted,delay){
    let timer;
    let firstTime = true;
    
    return function(){
        let closureThis = this;
        let closureArgs = arguments;
        
        if(timer){
            return false;
        }
        if(firstTime){
            fnToBeExecuted.apply(closureThis,closureArgs);
            firstTime = false;
        }
        
        timer = setTimeout(function(){
            clearTimeout(timer);
            timer = null;
            fnToBeExecuted.apply(closureThis,closureArgs);
        },(delay || 500));
    }
}

window.onresize = throttle(function(){console.log('throttle')},3000);

</script></body></html>

 

// 通用的单例模式
let getSingleton = function(fn)(){
    let instance;
    return function(){
        return instance || (instance = fn.apply(this,arguments));
    }
};
getSingleton(function(){//createSomethingThenReturn})

 

// AOP
Function.prototype.before = function (beforefn) {
    var _self = this;
    
    //闭包
    return function(){        
        // beforefn 和 _self 原来怎么调用的, 返回闭包后还是按照原来的方式调用
        // 因此 this 就是调用 beforefn 和 _self 的那个 this
        beforefn.apply(this,arguments);
        _self.apply(this,arguments)
    }
}

Function.prototype.after = function (afterfn) {
    var _self = this;
    return function () {
        _self.apply(this,arguments);
        afterfn.apply(this,arguments);
    }
    
}

 

posted @ 2021-10-12 23:08  ノ→_→(←_←  阅读(51)  评论(0编辑  收藏  举报