javascript - Maintain this in a method passed by reference -


in following example, send parameter method "lostthis" object "instobj", "this" window object.

var obj = function() {}; obj.prototype.lostthis = function() {     console.log('lostthis', instanceof obj, this); };  var instobj = new obj;  var caller = {     runfn: function(fn) {         fn();     } };  caller.runfn(instobj.lostthis); 

console response:

lostthis false window 

run example

in following example (slightly more complex) there different ways call methods of "instobj" same , others can keep "this" object.

var obj = function() {};  obj.prototype.methodrefhasthis = function() {     var t = this;     return function() {         console.log('methodrefhasthis ', t instanceof obj, t);     }; };  obj.prototype.methodreflostthis = function() {     console.log('methodreflostthis ', instanceof obj, this); };  obj.prototype.methodrefmaybethis = function() {     console.log('methodrefmaybethis ', instanceof obj, this); };  var instobj = new obj; var caller = {     runfn: function(fn) {         fn();     } };  // width jquery $('button')     .bind('click', instobj.methodrefhasthis())     .bind('click', instobj.methodreflostthis);  caller.runfn(instobj.methodrefhasthis()); caller.runfn(instobj.methodreflostthis); caller.runfn(function() {     instobj.methodrefmaybethis(); });​ 

console response:

methodrefhasthis  true obj methodreflostthis  false window methodrefmaybethis  true obj  methodrefhasthis  true obj methodreflostthis  false <button>​press here​</button>​ 

run example

i understand happens jquery assign method event, could call method "methodreflostthis" no lose "this" object passed reference?

thanks

solution @am_not_i_am , @dan_davies_brackett , @ben_lee

var obj = function() {}; obj.prototype.lostthis = function() {     console.log('lostthis', instanceof obj, this); };  var instobj = new obj;  var caller = {     runfn: function(fn) {         fn();     } };  caller.runfn(instobj.lostthis.bind(instobj)); caller.runfn($.proxy(instobj.lostthis, instobj)); 

console response:

lostthis true obj lostthis true obj   ​ 

run example

if don't want use 1 of techniques you've found work, can use function.prototype.bind bind calling context new function...

caller.runfn(instobj.lostthis.bind(instobj)); 

this returns new function when invoked, set calling context whatever passed first argument .bind().

any additional arguments passed .bind() set fixed arguments returned function.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -