Value unchanged when another function is called in javascript -


i reading article. related javascript. here, code sample article. please @ below.

function customobject(){   this.value = 2;   }     customobject.prototype.inc = function(){   this.value++;   }     function changer(func){   func();   }     var o = new customobject();     alert(o.value);     o.inc();   alert(o.value);    changer(o.inc);   alert(o.value); 

my question why value "o.value" unchanged when changer(o.inc) called ?

o.inc reference anonymous function:

function() {      this.value++; } 

whereas this scope in function executed. when run changer(o.inc), this pointing global, in browsers it's window. doesn't have o.

you bind scope this:

function changer(func, scope){      func.call(scope); // or apply }   changer(o.inc, o);  

or simply:

function changer(func){      func(); } changer(o.inc.bind(o)); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -