JS 基礎篇(代理模式)

2b勿擾發表於2020-01-20

保護代理

<script>
    //主體,傳送
    function sendMsg(msg) {
        console.log(msg);
    }
    //代理
    function proxySend(msg) {
        msg = msg.replace(/XT/, '');
        sendMsg(msg);
    }
    proxySend('XT,辛苦的碼農')
</script>

虛擬代理

<!-- scroll, resize,keyup 等事件頻繁觸發會引起卡頓 -->
function scrollHnader(name,age){
    console.log('螢幕滾動了');
}
function debounce2(fn,delay){
    delay = delay || 300;
    if(fn.id){
        clearTimeout(fn.id);
    }
    fn.id = setTimeout(function(){          
        fn();
     },delay);
}
window.onscroll = function(){
    debounce2(scrollHnader.bind(this,'laney'),500); 
}

快取代理

function add(){
    var arg = Array.from(arguments); //es6
     return arg.reduce(function(a,b){
          return a+b;
     })
}

var proxyAdd = (function(){
    var cache = [];
    return function(){
        var arg = Array.from(arguments).join(','); 
        if(cache[arg]){
            return cache[arg];
        } else {
            var ret=  add.apply(this,arguments);
            cache[arg] = ret;
            return ret;
        }
    }
})();

var k1= proxyAdd(1,2,3,4)
proxyAdd(10,20,30,40)
proxyAdd(10,20,30,40)//取快取
proxyAdd(10,20,30,40)//取快取

相關文章