oop - javascript object variable scope -


i have messagehelper object has idx var. want access , modify index method. thought 'this' i'm getting nan. clue?

var messagehelper = {         idx: 8,         formatdate: function(){             return function(text, render) {                 // // parse date                 var date = $.trim(render(text));                 var mom = moment(date);                 return mom.format("d/m/yy");             }         },         formatdatetime: function(){             [...]         },               getimportance: function(){             [...]         },         index: function(){             return function(text, render) {                 this.idx++;                 return this.idx;             }         }     }    

the value of this inside function depends on how function called. if want function called value this, simplest way use function.prototype.bind:

    index: function(){         return function(text, render) {             this.idx++;             return this.idx;         }.bind(this); // <--- here     } 

in example relied on fact outer function called this:

messagehelper.index() 

so inside it, this messagehelper. thus, messagehelper this inside function returned index well.

if plan stuff pass index function parameter somewhere, won't called expected , whole thing fail. in case should bind messagehelper:

var messagehelper = {   index : function(){}.bind(messagehelper); }  var myindex = messagehelper.index; myindex(); // return correct function, bound messagehelper 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -