Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of "this" in JavaScript

Tags:

javascript

I have a JavaScript class that looks like this:

function SomeFunction()
{
    this.doSomething(function()
    {
        this.doSomethingElse();
    });

    this.doSomethingElse = function()
    {

    }
}

This code throws an error because the scope of "this" inside the function that is passed into doSomething() is different that than the scope of "this" outside of that function.

I understand why this is, but what's the best way to deal with this? This is what I end up doing:

function SomeFunction()
{
    var thisObject = this;

    this.doSomething(function()
    {
        thisObject.doSomethingElse();
    });

    this.doSomethingElse = function()
    {

    }
}

That works fine, but it just feels like a hack. Just wondering if someone has a better way.

like image 752
Jon Kruger Avatar asked Feb 12 '10 18:02

Jon Kruger


1 Answers

That is the correct and commonly-accepted workaround. It's sort of kludgy but it's what everybody does. Typically this extra variable is named self, as in:

function SomeFunction()
{
    var self = this;

    this.doSomething(function()
    {
        self.doSomethingElse();
    });

    this.doSomethingElse = function()
    {

    }
}
like image 174
John Kugelman Avatar answered Oct 09 '22 13:10

John Kugelman