Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

6. The this Keyword > The this Keyword Refers to the Head Object in Nested Func...

The this Keyword Refers to the Head Object in Nested Functions

You might be wondering what happens to this when it is used inside of a function that is contained inside of another function. The bad news is in ES3, this loses its way and refers to the head object (window object in browsers), instead of the object within which the function is defined.

In the code below, this inside of func2 and func3 loses its way and refers not to myObject but instead to the head object.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var myObject = {
   func1: function() {
       console.log(this); // logs myObject
       var func2 = function() {
          console.log(this) // logs window, and will do so from this point on
          var func3 = function() {
              console.log(this); // logs window, as it's the head object
          }();
       }();
   }
}

myObject.func1();

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint