JavaScript · Programming

JavaScript ‘this’ keyword

This keyword is a mysterious keyword in JavaScript. It means different things depending on the context it is being used.

The three main manifestations of ‘this’ are:

  1. this refers to the window host object.
  2. “this” refers to the containing or outer function/object.
  3. “this” refers to the DOM element to which an event has been attached to.


The reason for the behaviour of this object lies in the way JavaScript handles scope.

This as window object

If “this” is used in a function defined directly in the global scope, then the function becomes part of the window object. In such functions, this refers to the window object.

var hello = 'Welcome';

function helloWorld() {
    alert(this); //alerts window
    alert(this.hello); //alerts Welcome
}

This as containing/outer function/object

When a function is defined inside another function/object, it obtains the this object as the reference to outer/containing function.

Function

function outerF() {this.name = 'outerF';}

outerF.prototype.innerF = function() 
{
    alert(this);
    alert(this.name);
}

var of = new outerF();
of.innerF();

Object Literal

var x = {
    "name" : "foo",
    "bar" : function(){alert(this);},
    "zar" : function(){return this.name;}
}

x.name;
x.bar(); // alerts object which is the type for x
x.zar();

var xcopy = x;
var name = xcopy.zar();
alert(name);

This as DOM element in event handler

If we use the traditional event registration model then the event handler gets the reference to this as the object defined in it. Inline event registration will not work as the this is not copied to the inline event handler and this will refer to the window object.

Assuming the following HTML element.

<p id="some-id">This is not that</p>
function clickedMe(){alert('Click ' + this.id);}

var p = document.getElementById('some-id');

p.onclick = clickedMe;

The inline event registration will NOT give the DOM element as reference to this. Inline registration causes this to refer to the window object.
We should avoid using this model in our code because it violates the principle of unobtrusive JavaScript and progressive enhancement.

<p id="some-id" onclick="clickedMe();">This is not that</p>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s