in the following example, to send as parameter to the method “lostThis” object “instObj”, “this” is the window object.
var obj = function() {};
obj.prototype.lostThis = function() {
console.log('lostThis', this instanceof obj, this);
};
var instObj = new obj;
var caller = {
runFn: function(fn) {
fn();
}
};
caller.runFn(instObj.lostThis);
Console response:
lostThis false Window
In the following example (slightly more complex) there are different ways to call the methods of “instObj” where it is the same and others where I can keep the “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 ', this instanceof obj, this);
};
obj.prototype.methodRefMaybeThis = function() {
console.log('methodRefMaybeThis ', this 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>
I understand that this happens with jQuery to assign the method to an event, but could I call the method “methodRefLostThis” no lose “this” object to be passed by reference?
thanks
Solution by @am_not_i_am , @Dan_Davies_Brackett and @Ben_Lee
var obj = function() {};
obj.prototype.lostThis = function() {
console.log('lostThis', this 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
If you don’t want to use one of the techniques that you’ve found to work, you can use
Function.prototype.bindto bind the calling context to a new function…This returns a new function that when invoked, will set the calling context to whatever you passed as the first argument to
.bind().Any additional arguments passed to
.bind()will be set as fixed arguments to the returned function.