Reputation: 11703
How can I keep the value of this
when I go inside a function I lost the previous value of this
For example in this case how can I got the access to the testFunction
.
admin = function()
{
this.testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: function()
{
this.testFunction();
// here I got an error undefined
}
});
}
}
I've tried to keep the value of this on a self var like this
this.self = this;
but not work
Upvotes: 3
Views: 99
Reputation: 23310
Another potentially effective approach which would avoid handling this
would be making the callbacks parameters:
admin = function()
{
this.testFunction = function()
{
alert('hello');
}
this.test2Function = function(successCallback)
{
$.ajax({
url:'',
success: function()
{
if(typeof(successCallback) === 'function') {
successCallback();
}
}
});
}
}
//usage:
admin.test2Function(admin.testFunction);
Upvotes: 0
Reputation: 3914
admin = function()
{
var top = this;
this.testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: function()
{
top.testFunction(); // should work :)
}
});
}
}
All local variables defined in a function, propagate (could be accessed) through WHOLE function, including all functions defined in that function.
So var top = this;
will carry it's value through all inner functions and objects declared inside of admin
.
Upvotes: 3
Reputation: 38919
All the answers are correct, just for the record, by referring the google style guide:
Because this is so easy to get wrong, limit its use to those places where it is required:
in constructors
in methods of objects (including in the creation of closures)
IMO, the best approach is Josh's answer.
Upvotes: 0
Reputation: 44916
You need to use a closure. The idomatic way of doing this in JavaScript is:
function foo(){
//Store this in outer scoped variable.
// It will be available to anything within this scope
var that = this;
innerCall(function(){
that.doSomething();
});
}
Upvotes: 5
Reputation: 9090
there are multiple ways it upto you and the big picture that which one suits
admin = function()
{
this.testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: this.testFunction
});
}
}
or
admin = function()
{
var testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: testFunction
});
}
}
or
admin = function() { this.testFunction = function() { alert('hello'); }
var testFucntion = this.testFunction;
this.test2Function = function()
{
$.ajax({
url:'',
success: function(){ testFucntion(); }
});
}
}
Upvotes: 1