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 > How Is the Value of this Determined?

How Is the Value of this Determined?

The value of this, passed to all functions, is based on the context in which the function is called at runtime. Pay attention here, because this is one of those quirks you just need to memorize.

The myObject object in the code below is given a property called sayFoo, which points to the sayFoo function. When the sayFoo function is called from the global scope, this refers to the window object. When it is called as a method of myObject, this refers to myObject.

Since myObject has a property named foo, that property is used.

Live Code

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

var foo = 'foo';
var myObject = {foo: 'I am myObject.foo'};

var sayFoo = function() {
   console.log(this['foo']);
};

// give myObject a sayFoo property and have it point to sayFoo function
myObject.sayFoo = sayFoo;

myObject.sayFoo(); // logs 'I am myObject.foo'
sayFoo(); // logs 'foo'

</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