Javascript 我可以扩大';这';在下面的例子中?
在使用jquery回调时,我发现不再定义“this”。我找到了一个解决办法,就是将“this”设置为另一个变量。例如,像这样:Javascript 我可以扩大';这';在下面的例子中?,javascript,jquery,Javascript,Jquery,在使用jquery回调时,我发现不再定义“this”。我找到了一个解决办法,就是将“this”设置为另一个变量。例如,像这样: function handler(DATA) { var myThis = this; $.post( 'file.php', DATA, function() { // THIS where I need access to 'this', but
function handler(DATA) {
var myThis = this;
$.post(
'file.php',
DATA,
function() {
// THIS where I need access to 'this', but its not available
// unless I've used the 'myThis' trick above
}
);
}
它是这样工作的,但我总是在寻找“正确的方式”或“更好的方式”来做事
这是最好的方式吗?或者还有别的吗?这很好。在我的项目中,我总是这样做,尤其是在Ajax调用中 但是,请确保将
var
放在myThis
之前,否则它将在全局范围内声明,这是您绝对不希望看到的
function handler(DATA) {
var myThis = this;
$.post(
'file.php',
DATA,
function() {
// THIS where I need access to 'this', but its not available
// unless I've used the 'myThis' trick above
}
);
}
我喜欢使用“自我”:
您也可以使用jQuery的代理方法……但在这种情况下,这可能会有些过分
function handler(DATA) {
var success = $.proxy(function(){
// use "this" in this function to refer to the scope
// you were assigning to "myThis" in your example
}, this);
$.ajax({
"url":"file.php",
"type":"post",
"data":DATA,
"success":success,
"error":function(){}
});
}
您可能希望在
myThis=this前面抛出一个var
代码>但是你这样做是很常见的做法是的,实际上我的代码中有var,但我没有复制/粘贴,不管是什么原因:)我希望有一种更平滑、更流畅的方法,但并不总是这样。
function handler(DATA) {
var success = $.proxy(function(){
// use "this" in this function to refer to the scope
// you were assigning to "myThis" in your example
}, this);
$.ajax({
"url":"file.php",
"type":"post",
"data":DATA,
"success":success,
"error":function(){}
});
}