Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of this.someFunction.call(this, param);

I've come across some code that has this sort of pattern in numerous places:

this.someFunction.call(this, param);

but it seems to me just a more verbose way of typing

this.someFunction(param)

The pattern sometimes appears inside a function which is provided as a callback. It happens to use Backbone, in case that's relevant. Something like this:

Backbone.View.extend({
    // other stuff ...

    someFunction: function(param) {
        // ...
    },
    anotherFunction: function() {
        this.collection.on("some_event", function() {
            this.someFunction.call(this, param);
        });
    }
});

Does the pattern actually have an effect that isn't the equivalent of this.someFunction(param) or was someone just nervous about the closure not capturing the correct this?

Thanks for any insights!

like image 779
Jeffrey Martinez Avatar asked Mar 18 '15 22:03

Jeffrey Martinez


1 Answers

Does the pattern actually have an effect that isn't the equivalent of this.someFunction(param)?

No, they are indeed the same. Assuming that this.someFunction is a function that inherits .call from Function.prototype (but that's nit-picking).

Looks like someone was overcautious, or the code is a remains of something that did not use this twice. Or maybe the author was aware of the this-context-in-callbacks issue but failed to handle it correctly.

like image 120
Bergi Avatar answered Oct 25 '22 10:10

Bergi