javascript - not able to change a value assigned to this object using .bind -


i'm using angular develop web app , i'm trying use function's .bind method assign value on method of 1 of controllers. looks this:

var welcomectrl = function (usermanager) {   this.partnername = usermanager.getname('partner');   this.yourname = usermanager.getname('you');   this.beginscan = false;   var self = this; };  welcomectrl.prototype.scanthumb = function (callback) {   function doscan() {     alert(this);     alert(this.beginscan);     this.finishedscanning = callback;     this.beginscan = true;   }    doscan.bind(welcomectrl)();  }; 

so happens directive passes scanthumb method service executes it, should trigger directive waiting this.beginscan true.

since service calls method , not called welcomctrl class, need bind this welcomectrl use .bind , pass in welcomectrl

this should work, when alert(this) welcomectrl function definition alerts fine, when alert(this.beginscan) undefined

am not understanding how .bind method works in circumstance?

whenever using object's inner function (in case, welcomectrl) this refers current object.

take following example:

var foo = function(){   this.thing = 'bar'; }  foo.prototype.setthing = function(newthing){   //our inner function   function doinnerthing(){     //this bound our current foo instance     console.log(this);     //setting our current foo.thing new value     this.thing = newthing;     };   //fire function, bound current object scope (foo)   doinnerthing.bind(this)(); };  foo.prototype.dothing = function(){   alert(this.thing); };  var newfoo = new foo(); var newfoo2 = new foo();  newfoo.setthing('newfoo'); newfoo.dothing(); //alerts 'newfoo', overridden value   newfoo2.dothing();//alerts 'bar', base value 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -