[英]How can I keep the value of `this` when I go inside a function?
我怎样才能保持价值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
}
});
}
}
我试图将这个值保持在这样的自变量上
this.self = this;
但不行
你需要使用一个闭包 。 在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();
});
}
admin = function()
{
var top = this;
this.testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: function()
{
top.testFunction(); // should work :)
}
});
}
}
函数中定义的所有局部变量,通过WHOLE函数传播(可以访问),包括该函数中定义的所有函数。
所以var top = this;
将通过admin
内部声明的所有内部函数和对象来传递它的值。
它有多种方式可供您使用,以及适合您的大图
admin = function()
{
this.testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: this.testFunction
});
}
}
要么
admin = function()
{
var testFunction = function()
{
alert('hello');
}
this.test2Function = function()
{
$.ajax({
url:'',
success: testFunction
});
}
}
要么
admin = function(){this.testFunction = function(){alert('hello'); }
var testFucntion = this.testFunction;
this.test2Function = function()
{
$.ajax({
url:'',
success: function(){ testFucntion(); }
});
}
}
另一种避免处理this
潜在有效方法是制作回调参数:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.