this inside function

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

Leave a Comment