Front End Engineering, May 2015

this

A JavaScript keyword that evaluates to different values in different execution contexts.

  • Global and global functions
    • In strict mode, this === undefined
    • In sloppy mode, this === window
  • Inside methods (even if the function was added to the object later)

    • Equal to object the method was called on, e.g.:

      var jake = {
        name: "Jake",
        greet: function(){
          console.log("Hi, my name is " + this.name);
        }
      }
      
      jake.greet() // this === jake
      var vagabondGreet = jake.greet;
      vagabondGreet(); // this === undefined (in strict mode)
      
  • jQuery
    • In event handlers, this === event.target. E.g.
      $('button').on('click', function(event) {
      // this === event.target
      // $(this) === jQuery wrapped element, allowing jQuery methods
      $(this).css({backgroundColor: 'green'});
      });