This
Regular Mode
  • this refer to the owner object
    1. // in a method
    2. var person = {firstName: "John", lastName : "Doe",
    3. fullName : function() {
    4. return this.firstName + " " + this.lastName; // refer to person
    5. }
    6. };
    7.  
    8. console.log(person.fullName());
    9.  
    10. // alone
    11. var x = this; // refer to window
    12.  
    13. console.log(x);
    14.  
    15. // in a function
    16. function f()
    17. {
    18. return this; // refer to window
    19. }
    20.  
    21. console.log(f());
    Strict Mode
  • this in a function is undefined
    1. "use strict";
    2.  
    3. // in a function
    4. function f()
    5. {
    6. return this; // undefined
    7. }
    8.  
    9. console.log(f());
    This in Event Handlers
  • Refers to the HTML element that received the event
    1. <button onclick="this.style.color='red'">Click</button>