JavaScript: the this keyword

In JavaScript, the this keyword points to the owner of the function it is contained within. If it occurs within a method as part of a class, it refers to the class itself, or rather the object instance of the class created when your code is executing. Out of the context of a class, this usually points to the global window object.

If you want to call a method and make sure that this refers to a different object than the one it would normally refer to, use apply or call. There's a slight difference between these two methods: the former expects any arguments you're passing to the function to be supplied as an array, while the latter does not. Examples:

var showMessage = function() {

var setMessage = function(message) {
  this.message = message;

// this points to window

showMessage(); // undefined
showMessage(); // 'Foo'

In these examples, the this keyword refers to the global object itself. Now we can create a class and force the this keyword to refer to our class instead of window.

var LogMessage = function() {
  this.message = '';

var myLogMessage = new LogMessage();, 'Foo');
setMessage.apply(myLogMessage, ['Foo']);; // 'Foo'

Leave a Reply

Note: Only a member of this blog may post a comment.