Closed ruipin closed 2 years ago
I would use this proposed enhancement. I am wrapping all the template drawing methods in my walled templates module, so I currently have a lot of repeated code. (I was actually just looking to see if libWrapper could do something like this when I saw this issue!)
Implemented in v1.12.0.0:
/**
* ...
*
* @param {any[]} options.bind [Optional] An array of parameters that should be passed to 'fn'.
*
* This allows avoiding an extra function call, for instance:
* libWrapper.register(PACKAGE_ID, "foo", function(wrapped, ...args) { return someFunction.call(this, wrapped, "foo", "bar", ...args) });
* becomes
* libWrapper.register(PACKAGE_ID, "foo", someFunction, "WRAPPER", {bind: ["foo", "bar"]});
*
* First introduced in v1.12.0.0.
*
* ...
*/
Sometimes users of libWrapper wish to bind the same function as a wrapper to multiple methods, and wish to distinguish which one is being called.
For example, if we have the wrapper function:
This can be achieved using
Function.prototype.bind
:This works, and will result in calls to
someFunction("foo", wrapped, ...args)
andsomeFunction("bar", wrapped, ...args)
, however thethis
variable within those functions will benull
. Due to the design ofFunction.prototype.bind
, there is no way to use it yet have the correct value forthis
.The alternative is to use an anonymous function, e.g.:
This will result in the correct value of
this
, however it involves extra code and also causes performance loss and stack trace pollution due to the extra function call.It would probably be a good idea to improve the libWrapper API, to support this natively, e.g.:
The exact name of the parameter (
bind
above) is subject to change, but it is meant as a replacement to the previous two solutions, and would take an array of arguments that would be passed to the function as-is beforewrapped
and any other parameters in the call.This would give the user the best of both worlds, i.e.
this
will be correct while the extra call (and corresponding performance loss & stack trace pollution) will be avoided.Ideally, the shim would also be updated to support this. From a cursory glance it would be a relatively simple change.