将变量设置为“this"是否有功能目的? [英] Is there a functional purpose for setting a variable to 'this'?
本文介绍了将变量设置为“this"是否有功能目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,有时当我查看其他人的代码时,他们会使用 var self = this;
或者在 jquery 中例如使用 var $self = $(this);
As in, sometimes when I look at code by other people, they will go var self = this;
or in jquery for example, go var $self = $(this);
这样做有什么特别的原因吗?
is there a particular reason for doing so?
推荐答案
正如其他人提到的,如果你想在另一个函数中使用它,你可以将一个变量设置为 $(this).
As others have mentioned, you could set a variable to $(this) if you wish to use it in another function.
实际示例是执行与页面上的事件相关的 ajax 调用.使用 JQuery:
On practical example would be when doing an ajax call tied to an event on the page. Using JQuery:
<script>
$(document).on("click", ".mySelector", function () {
// Where we are in the click event, $(this) refers to whatever
// element has a class of mySelector that was clicked
var self = $(this);
theDiv.html('');
$.ajax({
cache: false,
type: "GET",
url: "/SomeAjaxMethod",
data: { },
success: function (data) {
// Trying to access $(this) here will return undefined, as
// we are technically in the callback method
// Where our event is based on a class, there is likely more
// than one element on the page with the class, so it would be
// difficult to get the exact element again without some other code
self.html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Ajax failed.")
}
}); // end ajax call
}); // end on mySelector class click
</script>
或:
<script>
$(document).ready(function () {
$('.foo').click(function () {
var self = $(this); // Whatever element that was clicked with foo class
$('.bar').each(function () {
var bar = $(this); // Current iteration of bar element in the loop
var baz = self; // self is still the initial value, but $(this) is not
}); // end bar loop
}); // end foo click
}); // end doc ready
</script>
这篇关于将变量设置为“this"是否有功能目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文