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 > Controlling the Value of this Using call() or apply()

Controlling the Value of this Using call() or apply()

The value of this is normally determined from the context in which a function is called (except when the new keyword is used—more about that in a minute), but you can overwrite/control the value of this using apply() or call()to define what object this points to when invoking a function. Using these methods is like saying: “Hey, call X function but tell the function to use Z object as the value for this.” By doing so, the default way in which JavaScript determines the value of this is overridden.

Below, we create an object and a function. We then invoke the function via call() so that the value of this inside the function uses myObject as its context. The statements inside the myFunction function will then populate myObject with properties instead of populating the head object. We have altered the object to which this (inside of myFunction) refers.


  

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