Loading

Javascript's 'this'

by drk last updated on 2014/09/13 ( programming / javascript )


What does 'this' point to?

  • Depends on how that function was called.
  • Look for the object that is immediately to the left of the function that is being called, to know what 'this' will point to.
  • In an event handler function, 'this' points to the html element that triggered the event.
  • When inside a constructor (a function called with 'new'), 'this' points to the created object.

Examples

Global scope

    // variable defined in the global space (not inside a function)
var GLOBAL = 1;

    // we can access it normally
console.log( GLOBAL );           // 1

    // 'window' in the browser is the global context,
    // so this is equivalent to above
console.log( window.GLOBAL );    // 1

    // 'this' in the global space points to window
console.log( this.GLOBAL );      // 1

Print value

function printValue()
{
console.log( this.value );
}

var value = 1;

var obj = {
        value: 2,
        other: {
            value: 3
            }
    };

    // called from 'window' (same as window.printValue()),
    // so this.value is window.value
printValue();                   // 1

    // called with 'obj', so this.value is obj.value
printValue.call( obj );         // 2

    // called with 'obj.other', so this.value is obj.other.value
printValue.call( obj.other );   // 3

Other print value

var value = 1;

var obj = {
        value: 2,
        printValue: function()
            {
            console.log( this.value );
            }
    };


obj.printValue();       // 2

    // get a reference to the function
var otherPrintValue = obj.printValue;

    // same as window.otherPrintValue()
otherPrintValue();      // 1

Event handlers

<a id="test">click me</a>
var test = document.querySelector( '#test' );

test.onclick = function()
    {
    console.log( this.innerHTML );  // 'click me'

        // same as
    console.log( test.innerHTML );  // 'click me'
    };

New object

function Position( x, y )
{
this.x = x;
this.y = y;
}

var a = new Position( 1, 2 );

console.log( a.x );     // 1
console.log( a.y );     // 2

Event handlers inside of a constructor

function Element()
{
var _this = this;   // get a reference to the Element object created

this.value = 0;     // 'this' here, points to the Element object created

var p = document.createElement( 'p' );

p.innerHTML = this.value;
p.onclick = function()
    {
    var htmlElement = this;     // could use the 'p' variable as well

        // 'this' here points to the html element,
        // so if you want to get the element object,
        // you need to save a reference to it outside of this function
    _this.value++;
    htmlElement.innerHTML = _this.value;
    };

document.body.appendChild( p );
}
back

Categories