Try to summarize the usage of “this” with examples

  • Every function created with the function keyword or with the method shorthand has its own “this”, and it generally binds to “who” called it.
  • Arrow functions don’t bind “this” to anything, the “this” inside depends on the surrounding context

Example 1

“handler” declared by error function here, that means the “this” is nothing, just same as outside the handler, thus the output is Window object

const handler = () => {
 console.log(this);
};
btn1.addEventListener('click', handler);

Output

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

#es6-in-depth #self-learning #javascript-tips #es6-js #self-taught #javascript

ES6 JavaScript— “this” keyword
1.50 GEEK