1. 程式人生 > >js中的裝飾器。攔截器。細細品味 bind apply call

js中的裝飾器。攔截器。細細品味 bind apply call

var zlw = {
    name: "zlw",
    sayHello: function (age) {
         console.log("hello, i am ", this.name + " " + age +" years old");
     }
};


var  xlj = {
    name: "xlj",
};


zlw.sayHello(24);
VM273:4 hello, i am  zlw 24 years old
undefined
zlw.sayHello.bind(xlj, 24)()

VM273:4 hello, i am  xlj 24 years old

zlw.sayHello.call(xlj, 24);// 
hello, i am xlj 24 years old zlw.sayHello.apply(xlj, [24])

function debounce(fn, delay){// 維護一個 timer
  let timer =null;// 能訪問 timer 的閉包returnfunction(){// 通過 ‘this’ 和 ‘arguments’ 獲取函式的作用域和變數
    let context =this;
    let args = arguments;// 如果事件被呼叫,清除 timer 然後重新設定 timer
    clearTimeout(timer);
    timer 
= setTimeout(function(){      fn.apply(context, args);}, delay);}
}