Bind function without thisArg

Andrea Giammarchi andrea.giammarchi at gmail.com
Mon Jan 14 14:47:33 UTC 2019


It's not so easy to implement in user land, not because it's difficult to
do so:

```js
Function.prototype.bindArgs = (...args) => {
  const fn = this;
  return function (...moar) {
    return fn.apply(this, args.concat(moar));
  };
};
```

rather because of the bloat it produces once transpiled:
https://bit.ly/2SULtFZ

To avoid bloat and `arguments` leaking here and there, one must write
something like:

```js
function slice() {
  const arr = [];
  for (let {length} = arguments, i = +this; i < length; i++)
    arr.push(arguments[i]);
  return arr;
}

Function.prototype.bindArgs = function () {
  const args = slice.apply(0, arguments);
  return function () {
    const moar = slice.apply(0, arguments);
    return fn.apply(this, args.concat(moar));
  };
};
```

which is still a hell of a boilerplate compared to a native `const ba =
fn.bindArgs.apply(fn, arguments);` or `fn.bindArgs(...arguments)` for short.

+1 for having this in core


On Mon, Jan 14, 2019 at 12:48 PM T.J. Crowder <
tj.crowder at farsightsoftware.com> wrote:

> Although this is easy enough to implement in userland, frankly so was
> `bind`. I'd say it comes up often enough to consider. PrototypeJS (remember
> PrototypeJS?) called it `curry`.
>
> I'd think the specification changes for it would be minimal as well,
> basically A) Allowing Empty as boundThis in BoundFunctionCreate and
> [[BoundThis]] on functions; B) Updating [[Call]] on Bound Functions to use
> thisArgument when boundThis is Empty; creating a new `Function.prototype`
> method (`curry` would be the obvious -- and almost certainly **not**
> websafe -- name) to call BoundFunctionCreate with Empty for boundThis.
>
> But I'd be interested to know how difficult it is for JavaScript engines
> to implement, since Empty is largely a spec-level concept and it's valid
> (in strict mode) to use `null` and `undefined` as boundThis...
>
> -- T.J. Crowder
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20190114/55a3d3f6/attachment-0001.html>


More information about the es-discuss mailing list