2

When I use console.log to print 'this' in console, regular function print DOM element whereas fat function prints 'Window' element. Why is that so?

    // case 1
    $('.test').each(function(){
   console.log(this);
      return 0;
    });

    // case 2
    $('.test').each(()=>{
   console.log(this);
      return 0;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
smarber
  • 4,829
  • 7
  • 37
  • 78
Srikanth Sharma
  • 1,509
  • 2
  • 15
  • 27

1 Answers1

0

Arrow functions in javascript does not bind to their own this by definition. It is a feature which was intended to make an object oriented style of programming more convenient.

The link below posts some examples of why it is convenient to not bind to its own this when programming in an object oriented style.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

mikaelrs
  • 335
  • 1
  • 10