なぜこれほど多くのjqueryプラグインで$(this)が$ thisを指すように設定されているのか疑問に思いました。ページに次の2つのプラグインが含まれている場合、例を次に示します。
(function($) {
jQuery.fn.pluginOne = function() {
return this.each(function() {
$this = $(this); <--
alert($this);
});
};
})(jQuery)
(function($) {
jQuery.fn.pluginTwo = function() {
return this.each(function() {
$this = $(this); <--
alert($this);
});
};
})(jQuery)
domreadyで両方のプラグインを呼び出すと:
$(document).ready({
$('.myClass').pluginOne();
$('.myOtherClass').pluginTwo();
});
最初のプラグインは2番目のプラグインから$thisを取得します...それが$(this)をローカル変数にポイントしている間:
(function($) {
jQuery.fn.pluginTwo = function() {
return this.each(function() {
var trigger = $(this); <--
alert(trigger);
});
};
})(jQuery)
もちろん、すべてがうまくいくはずです...
だから私の質問は...いつ$thisを使うべきですか?
ありがとう