Paul
Paul

Reputation: 26650

"this" in a nested JavaScript function

function TheTable(calculateButtonId)
{
    this.errorsBlock = document.getElementById("Some Value");

    var addError = function(text) {
        this.errorsBlock.innerText += text + "\n";
    }

    var customHandler = function(desc, page, line, chr) {
        addError("[" + line + "] " + desc);
        return true;
    }
    this.init = function() {
        window.onerror = customHandler;
        ......................
    }
    this.init();
}

var table = new TheTable("BtnId");

as soon as I changed this.addError to var addError it started to thow an error:

Cannot set property 'innerText' of undefined

Could you clarify, what am I referencing by this inside of var-function?

Upvotes: 0

Views: 62

Answers (2)

Wayne
Wayne

Reputation: 60414

A couple things:

  • Whenever you invoke a function using the new keyword -- e.g. new TheTable("BtnId") -- you create a new instance of that type. The value of this inside that constructor refers to this new instance.

  • You can add arbitrary properties to this new instance.

  • In general, when you invoke a function that has been assigned to this new object, then the value of this inside the function is that same instance.

  • The var keyword creates a variable scoped to its nearest enclosing function. In general, when you invoke functions of this type (i.e. functions created as global or local variables), the value of this inside them is window.

So when you do this:

this.errorsBlock = document.getElementById("Some Value");

this.addError = function(text) {
    this.errorsBlock.innerText += text + "\n";
}

this.addError("whatever");

...then the value of this inside addError refers to the same object that errorsBlock was assigned to and the call succeeds. However, when you change it to this:

var addError = function(text) {
    this.errorsBlock.innerText += text + "\n";
}

addError("whatever");

...then the value of this inside addError is window and window probably doesn't have any function property named errorsBlock and the call fails.

Upvotes: 2

function TheTable(calculateButtonId) {
    this.errorsBlock = document.getElementById("Some Value");
    var self = this;
    var addError = function(text) {
        self.errorsBlock.innerText += text + "\n";
    }
}

this in javascript is always context under which function is running.

Upvotes: 1

Related Questions