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!


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.


I don't see any reasons to use such way of function call in code you provided. Here is better to use direct function call like this (if you need no modification with arguments)

this.collection.on("some_event", this.someFunction, this); 

or

this.collection.on("some_event", function() {
    this.someFunction(//some modified args)
}, this); 

And let me provide the example of proper usage of .call . Sure u've seen this:

Array.prototype.slice.call(arguments, 2); 

As arguments is not an array, we can 'borrow' Array method to operate with arguments . If you will try to call slice on arguments you will get an error

链接地址: http://www.djcxy.com/p/25240.html

上一篇: Docker中的Android模拟器

下一篇: this.someFunction.call的用途是什么(this,param);