this inside function

In JavaScript, the convention (and this is only a convention) is that any function that begins with a capital letter is to be used as a constructor. Then, one would call

var foo = new Foo() and this would refer to the newly created object that is about to be referenced by foo.

Of course, there is nothing stopping you from calling Foo() on its own, in which case this would then refer to the object from which the function was called. To avoid confusion, that is not recommended.


The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object.

It's used in OOP code, to refer to the class/object the function belongs to For example:

function foo() {
    this.value = 'Hello, world';

    this.bar = function() {
        alert(this.value);
    }
}

var inst = new foo();
inst.bar();

This alerts: Hello, world

You can manipulate which object this refers to by using the apply() or call() functions. (A very very handy feature at times)

var bar1 = new function() {
    this.value = '#1';
}
var bar2 = new function() {
    this.value = '#2';
}

function foo() {
    alert(this.value);
}

foo.call(bar1); // Output: #1
foo.apply(bar2, []); // Output: #2

Read what Douglas Crockford has to say on the matter, to quote him from A Survey of the JavaScript Programming Language:

A function is an object. It can contain members just as other objects. This allows a function to contain its own data tables. It also allows an object to act as a class, containing a constructor and a set of related methods.

A function can be a member of an object. When a function is a member of an object, it is called a method. There is a special variable, called this that is set to the object when a method of the object is called.

For example, in the expression foo.bar(), the this variable is set to the object foo as a sort of extra argument for the function bar. The function bar can then refer to this to access the object of interest.

In a deeper expression like do.re.mi.fa(), the this variable is set to the object do.re.mi, not to the object do. In a simple function call, this is set to the Global Object (aka window), which is not very useful. The correct behavior should have been to preserve the current value of this, particularly when calling inner functions.

Also 'this' can change depending on how your function is invoked, read on apply function and call function.

I would recommend that you spend time learning form one of JavaScript's greatest minds in his (free) presentations, linked from here.