0

let counter =0;
const getData =()=>{
    console.log('api called');
    counter++;
    console.log("counter",counter);
}

const debounce = function(fn,de){
    let timer;
    return function(){
        let context = this,args=arguments;
        console.log("context",this);
        console.log("arguments",args);
        clearInterval(timer);
        timer = setTimeout(()=>{
            fn.apply(context,arguments)
        },de);
    }
}


const betterFunction = debounce(getData,3000);
betterFunction();

A simple console log of the context in the above code prints window ?Why is it so and another thing is that why context has passed to the inner function when context is actually a window .

jammy
  • 591
  • 1
  • 9
  • 26
  • 4
    What are you expecting `this` to reference? `debounce` is being initiated as a simple function call, not as a method of any object, so its context is Global. – Scott Marcus Aug 13 '19 at 21:24
  • Since `getData` is an arrow function, you can't change its context with `apply()`. – Barmar Aug 13 '19 at 21:27
  • The default context in ordinary function calls is the global object, which is `window` in browsers. – Barmar Aug 13 '19 at 21:29
  • "*why context has passed to the inner function when context is actually a window*" - the execution "context" (stack frame) has nothing to do with the `this` keyword "context" (which is more like an invisible argument). – Bergi Aug 13 '19 at 21:54

0 Answers0