javascript - Using "this" inside named function on a jQuery plugin -


i'm trying write simple jquery plugin , need code run on both load , window resize wrote function inside plugin.

jquery(document).ready(function($) {

(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(); 

the problem 'this' doesn't seem recognized inside function. tried passing function argument:

enable_responsive_nav( ) 

...but error on console saying hasclass() 'is not function'.

i guess without function out , bind window resize event outside plugin, i'm trying keep single call , i'm sure i'm missing simple.

one common solution create local variable called that or self in scope this has expected value, , refer local variable in scope of inner function:

(function( $ ) {      $.fn.responsivenav = function() {         var self = this; // local variable         function enable_responsive_nav() {              if( self.hasclass('class') ) { // self in scope               //do stuff             }          }          $(window).resize(function(e) {             enable_responsive_nav();         });         enable_responsive_nav();          return this;      };  }( jquery ));  $('nav').responsivenav(); 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -