javascript - How to maintain reference to an instance, when using the setTimeout callback? -


how maintain reference instance, when using settimeout callback? e.g:

in viewmodel (using knockout)

var myvm = function () {   this.myfunc = function () {     settimeout("this.mycallback()", 2000);   };   this.mycallback = function() { this.myobservable(true); } } 

this fails.

you can add private field :

var myvm = function () {     var self = this;     this.myfunc = function () {         settimeout(self.mycallback, 2000);     };     this.mycallback = function() { self.myobservable(true); } } var vm = new myvm(); 

have @ rp niemeyer's answer.

i hope helps.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -