/ / jQueryプラグインの名前付き関数内で「this」を使用する-javascript、jquery、jquery-plugins

jQueryプラグインで "this"という名前の関数を使用する - javascript、jquery、jquery-plugins

単純なjQueryプラグインを作成しようとしていますが、ロードとウィンドウのサイズ変更の両方で実行するコードが必要なので、プラグイン内に関数を作成しました。

jQuery(document).ready(関数($){

(function( $ ) {

$.fn.responsiveNav = function() {

function enable_responsive_nav() {

if( this.hasClass("class") ) {
//do stuff
}

}

$(window).resize(function(e) {
enable_responsive_nav();
});
enable_responsive_nav();

return this;

};

}( jQuery ));

$("nav").responsiveNav();

問題は、「this」が関数内で認識されないようだということです。関数の引数として渡してみました:

enable_responsive_nav( this )

...しかし、コンソールにhasClass()は「関数ではない」というエラーが表示されます。

私は関数なしでそれを行うことができ、プラグインの外側でウィンドウサイズ変更イベントをバインドできると思いますが、私はそれを単一の呼び出しに維持しようとしています。

回答:

回答№1は1

一般的な解決策の1つは、というローカル変数を作成することです that または self 範囲内 this 期待される値を持ち、内部関数のスコープ内のローカル変数を参照するには:

(function( $ ) {

$.fn.responsiveNav = function() {
var self = this; // local variable
function enable_responsive_nav() {

if( self.hasClass("class") ) { // self is in scope
//do stuff
}

}

$(window).resize(function(e) {
enable_responsive_nav();
});
enable_responsive_nav();

return this;

};

}( jQuery ));

$("nav").responsiveNav();

回答№2の場合は1

関数の引数として渡してみました:

enable_responsive_nav( this )

チェーンをたどってみましょう:

jQueryはあなたのイベントコールバックを呼び出します this その DOM要素 (jQueryオブジェクトではなく)イベントがフックされた。だからあなたはこれを行うことができます:

enable_responsive_nav( $(this) );

〜と

if( arg.hasClass("class") ) {
//do stuff
}

または

enable_responsive_nav.call(this);

〜と

if($(this).hasClass("class") ) {
//do stuff
}