this & context - luk-swietlik/js GitHub Wiki

1. Function form

In function form 'this' point at the global object (window in browser) even if function is inside other function.

var txt,
    getTxt;

txt = 'outside txt';

getTxt = function() {
    var txt;

    txt = 'getName txt';
    console.log(this.txt); // 'outside txt'
};
getTxt();

Function inside other function:

var txt,
    getTxt;

txt = 'outside txt';

getTxt = function() {
    var txt,
        getTxtInside;

    txt = 'getTxt txt';
    getTxtInside = function() {
        var txt;
        
        txt = 'getTxtInside txt';
        console.log(this.txt); // 'outside txt'
    };
    getTxtInside();
};
getTxt();

2. Method form

In method form 'this' point at the object which this method belong to, so methods has reference to the object. Function defined inside method doesn't inherit 'this' from method, but point at the global object.

var obj;

obj = {
    txt: 'obj txt',
    getTxt: function(str) {
        console.log(str, this.txt); // 'Lorem', 'obj txt'
        console.log(str, txt); // Uncaught ReferenceError: txt is not defined => becouse it check for window.txt
    }
};
obj.getTxt('Lorem');

Notice:

var obj,
    foo,
    fooFix;

obj = {
    bar: function() {
        console.log(this);
    }
};
obj.bar(); // 'this' point at the 'obj'
foo = obj.bar;
foo(); // 'this' point at the global object (window)
fooFix = foo.bind(obj);
fooFix()  // 'this' point at the 'obj'

3. Constructor form

Call function with 'new' operator. It create new object which 'this' indicates. If this function doesn't have defined 'return' it returned 'this' by default (not 'undefined'). In 'return' we can only put object-type element, becouse other types interpreter will ignore and return 'this'. // TODO: examples

var Car,
    newCar;

Car = function(typeName) {
    this.type = typeName;
    this.showType = function () {
        console.log('Car type: ' + this.type);
    }
    return this; // optional, becouse it return 'this' by default
};

newCar = new Car('Honda');
newCar.showType(); // 'Car type: Honda'

Function defined inside constructor doesn't inherit 'this' from it, but point at the global object:

var Outside,
    fn

Outside = function() {
    return function inside() {
        console.log(this);
    };
};
fn = new Outside();
fn(); // 'this' point at the global object (window)

An example of protection for lack of 'new' operator:

Car = function(typeName) {
    if (!(this instanceof Car)) {
        return new Car(typeName);
    }
    // rest of code...
};

4. Event handler

'this' point at the DOM element that triggered the event

5. apply, call, bind