bind2
Enhanced Javascript
bind()
function.
Why ?
Because the [[BoundThis]]
internal properties of a bound function are not programmatically accessible, and you might need to get the context of a function without executing it. This lib also provides some tooling around the bind
mechanism.
Features
- Does not break the original
bind
API. - Immutable.
- New properties assigned to each bound function (using
bind2()
) :unbind()
(Function). Will return the original unbound function.unbound
(Function). Reference to the original unbound function.context
(Any). Get the function context without executing it.bound
(Boolean). Returnstrue
if the function has been bound withbind2
.bind2(context, ...parameters)
(Function). Re-bind the function. (Note :bind()
still exists.)
Examples
const bind2 = ; { return thishello;}const context = hello: 'world' ; // Native `bind()`.const boundFn = test;console; // undefinedconsole; // undefinedconsole; // undefinedconsole; // TypeError: bound2Fn.unbind is not a functionconsole; // 'world' // `bind2()`.const bound2Fn = ;console; // { hello: 'world' }console; // trueconsole; // [Function: test]console; // [Function: test]console; // 'world'
API
const bind2 = ;
bind2(fn, thisArg[, arg1[, arg2[, ...]]])
This function is a wrapper the native bind()
function.
-
Arguments :
fn
(Function) : the function to bind.thisArg
: The value to be passed as thethis
parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using thenew
operator. When usingbind
to create a function (supplied as a callback) inside asetTimeout
, any primitive value passed asthisArg
is converted to object. If no arguments are provided tobind
, thethis
of the executing scope is treated as thethisArg
for the new function.arg1, arg2, ...
: Arguments to prepend to arguments provided to the bound function when invoking the target function.
-
Returns : a copy of the given function with the specified this value and initial arguments.
bind2.fn(fn, thisArg[, arg1[, arg2[, ...]]])
Alias to bind2(fn, thisArg[, arg1[, arg2[, ...]]])
.
bind2.define()
Alias to bind2.wrap(Function.prototype)
.
This will mutate the Function
's prototype, thus adding the bind2()
and bound
properties to every function. It is recommended to execute this once, in the beginning of the script.
e.g.:
const bind2 = ; // Wrap `Function.prototype`.bind2; { return thishello;}const context = hello: 'world' ; // Use the new `bind2()` function.const boundFn = test;console; // { hello: 'world' }
License
MIT
Don't forget to 🌟 Star 🌟 the repo if you like this npm package !
Your feedback is appreciated