this inside function

Frank T. Icali picture Frank T. Icali · Dec 26, 2009 · Viewed 45.3k times · Source

My question is:

function Foo()
{
   this.foo = "bar"; // <- What is "this" here?
}

From what I can tell it depends on how Foo is used, i.e. as a constructor or as a function. What can this be in different circumstances?

Answer

Atli picture Atli · Dec 26, 2009

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