I am going through some code left behind by some long-gone developers and came across this:
Function.prototype.binding = function ()
{
if(arguments.length < 2 && typeof arguments[0] == "undefined") return this;
var __method = this, args = jQuery.makeArray(arguments), object = args.shift();
return function()
{ return __method.apply(object, args.concat(jQuery.makeArray(arguments))); };
};
and it is referenced elsewhere in a couple of places, this DataTables callback function is representitive:
"fnRowCallback": function (nRow, aData, iDisplayIndex)
{
nRow = this.options.fnRowCallback(nRow, aData, iDisplayIndex);
return nRow;
}.binding(this),
I think that what this is accomplishing is to set the this context in the function to the object passed into the .binding; is that correct? And is this way of doing that considered a good practice?
Thanks, Matthew
2 Answers 2
I think that what this is accomplishing is to set the
thiscontext in the function to the object passed into the .binding
Correct. Also it optionally accepts some extra arguments, which get passed into the function at call time. So if you did obj.f.binding(obj, 1, 2, 3)(4, 5, 6), the arguments received by obj.f would be 1, 2, 3, 4, 5, 6.
This method reproduces the standard ECMAScript Fifth Edition method Function#bind, but is named differently, presumably as it is not completely compliant with the interface defined by that method.
2 Comments
Function#bind where possible... not sure it's worth the bother of changing an old project, though. FWIW I think it's relatively unlikely that anything is relying on the difference between binding and bind (mainly to do with using the bound function as a constructor).what the code is doing is adding a method, binding to the Function prototype. Since Function is a javascript object (functions are objects in javascript), this basically adds a method to default javascript behavior.
This is a common practice in js frameworks. This particular method appears to allow you to set the scope of the method. In your second example, you could change binding(this) to binding(someObj), and when the method executes, this in the scope of the method would be someObj.