Saturday, December 5, 2020

use This keyword with Arrow Function in Javascript implementation

 when we write JavaScript function with Arrow to eliminate the function key, we must be extra caution, since THIS keyword object reference will be determine during the runtime, if the function is in the global scope, then THIS will point to the window object. if the function is pointing within the object, then THIS will only point to the object itself.

here is a simple example.

print: (delay=3000)=> {
    setTimeout(() => {
    console.log(this === window)
    }, delay)
}

the output is true. since THIS is execute with under the global scope.


after I change the Arrow function to a regular function, then  THIS key is reference to the object level

function print(delay=3000){
    setTimeout(() => {
    console.log(this === window)
    }, delay)
}

though arrow function is very handy in the javascript implementation, but we still have use it with care.




No comments:

Post a Comment