JavaScript object literal. Why can't I refer to a method via "this"? -


this question has answer here:

why can't refer method of javscript object using "this"? example in open(); method - why can't call this.init(); ?

    var mymodule = {          //initialize dek. append html structure body         init: function() {             if (!$('.mwdek').length) {                 var dek = $(tpl);                 dek.find('.d-nav-close').on('click', function(e) {e.stoppropagation();e.preventdefault();                     this.destroy();                 });                 dek.appendto('body');             }             //var dek = $('.mwdek');          },          //opens deck, makes visible         open: function() {             if (!$('.mwdek').length) {                 this.init();             }             $('.mwdek').addclass('active');         },          //removes deck html page         destroy: function(messages) {             $('.mwdek').remove();         },          //pass in header text content         setheadertext: function() {          }       }; 

the logic looks apart 1 issue in init function involving this variable. in statement object.method(), within method function, this refers object. keep in mind.

now, here's problematic portion of code:

init: function() {     if (!$('.mwdek').length) {         var dek = $(tpl);         dek.find('.d-nav-close').on('click', function(e) {             e.stoppropagation();             e.preventdefault();             this.destroy();     //this line has issue!         });         dek.appendto('body');     } } 

the this variable on line commented inside of anonymous function you've written (function(e) {...}). function provided jquery run when appropriate click occurs. jquery deciding how call function, means jquery understands this refer when function called. in code, rely on this pointing instance of dek, isn't case. in order solve problem can following (choosing name variable that common convention):

init: function() {     var = this; //maintain reference "this" inside anonymous functions     if (!$('.mwdek').length) {         var dek = $(tpl);         dek.find('.d-nav-close').on('click', function(e) {             e.stoppropagation();             e.preventdefault();             that.destroy();     //originally "this.destroy();"         });         dek.appendto('body');     } } 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -