1

I often use a construct like this:

var $this, url, callback; //some private vars
loadCallback = function($that, url, callback) {
    return function(responseText, textStatus, req) {
        ...
    };
})($this, url, callback)

However that is not quite comfortable. Is there some alternative?
I already took a look at jQuery.proxy, but that functions seems to fix the "this" variable so loadCallback can not get called applying another "this" context.

1
  • There are other ways to do it, but they all generally do the same thing. Either you change the context, pass an additional parameter, or store it in a parent scope (or any scope that the child scope has access to) Commented Jan 23, 2014 at 22:59

1 Answer 1

2

In modern browsers use bind. Implement your own simple version like this:

function bind(fn, _this) {
    var _args = Array.prototype.slice.call(arguments, 2); 
    return function() {
        return fn.apply(_this, _args.concat(Array.prototype.slice.call(arguments)));
    }
}

Usage:

var loadCallback = bind(function(url, responseText, textStatus, req) {
    console.log(url, responseText)
}, this, url);

A more complete polyfill can be found on MDN.

Sign up to request clarification or add additional context in comments.

2 Comments

what browsers are supported?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.