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.
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()
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With