this当我进入函数时,如何保留我丢失之前值的值this
例如,在这种情况下,我如何才能访问testFunction.
admin = function()
{
this.testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: function()
{
this.testFunction();
// here I got an error undefined
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我试图将这个值保持在这样的自变量上
this.self = this;
Run Code Online (Sandbox Code Playgroud)
但不行
你需要使用一个闭包.在JavaScript中执行此操作的惯用方法是:
function foo(){
//Store this in outer scoped variable.
// It will be available to anything within this scope
var that = this;
innerCall(function(){
that.doSomething();
});
}
Run Code Online (Sandbox Code Playgroud)