Last active
March 27, 2021 18:29
-
-
Save WebReflection/40e68a4f603ef788121a to your computer and use it in GitHub Desktop.
Function.prototype.bind performance problem solved in JS … (at least for 90% of common cases without partial args)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jslint indent: 2 */ | |
(function (FunctionPrototype) { | |
'use strict'; | |
var originalBind = FunctionPrototype.bind; | |
if (!originalBind.patched) { | |
Object.defineProperty( | |
FunctionPrototype, | |
'bind', | |
{ | |
configurable: true, | |
value: function bind(context) { | |
var callback = this; | |
return arguments.length === 1 ? | |
function () { return callback.apply(context, arguments); } : | |
originalBind.apply(callback, arguments); | |
} | |
} | |
); | |
FunctionPrototype.bind.patched = true; | |
} | |
}(Function.prototype)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The edge case is the last statement. When
boundFunction
is called through thenew
operator, the receiver (this
) is set to the object being created bynew
, not the originalcontext
object.I'm not sure, but this behavior may've been designed to allow constructor functions to take advantage of
bind
's partial application without the undesired side effect of settingthis
. For example:The code above would not work as intended if the bound function received
this == null
when invoked throughnew
. Of course, there are other ways of achieving the same effect.