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 > Working Around the Nested Function Issue by Leveraging th...

Working Around the Nested Function Issue by Leveraging the Scope Chain

So that the this value does not get lost, you can simply use the scope chain to keep a reference to this in the parent function. The code below demonstrates how, using a variable called that, and leveraging its scope, we can keep better track of function context.

Live Code

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

var myObject = {
   myProperty: 'I can see the light',
   myMethod : function(){
       var that = this; /* store a reference to this (i.e., myObject) 
                        in myMethod scope */
       var helperFunction function() { // child function
          // logs 'I can see the light' via scope chain because that = this
          console.log(that.myProperty); // logs 'I can see the light'
          console.log(this); // logs window object, if we don't use "that"
       }();
   }
}

myObject.myMethod(); // invoke myMethod

</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 10-Day Trial


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