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

I came across some code that has this structure in many places:

this.someFunction.call(this, param); 

but it seems to me that this is just a more detailed input method

 this.someFunction(param) 

A pattern sometimes appears inside a function that is provided as a callback. It happens to use the Trunk, in case it is necessary. Something like that:

 Backbone.View.extend({ // other stuff ... someFunction: function(param) { // ... }, anotherFunction: function() { this.collection.on("some_event", function() { this.someFunction.call(this, param); }); } }); 

Does the template really have an effect that is not equivalent to this.someFunction(param) , or was someone just nervous about closing without fixing the correct this ?

Thanks for any ideas!

+7
javascript
source share
2 answers

Does the template really have an effect that is not equivalent to this.someFunction(param) ?

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

It looks like someone was excessive, or the code remained something that didn't use this twice. Or perhaps the author was aware of the problem this -context-in-callbacks , but could not handle it correctly.

+2
source share

I see no reason to use this method of calling a function in the code that you provided. It is better to use a direct function call like this (unless you need changes with the 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 give an example of the correct use of .call . Of course you saw this:

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

Since arguments not an array, we can "borrow" the Array method to work with arguments . If you try to call slice on arguments , you get an error

+1
source share

All Articles