hgiesel
hgiesel

Reputation: 5648

Make functional functions OO functions in Javascript

Let's say I have this easy id function:

let id = a => a

And now I want to make it a OO-style method, without redefining it, i.e.

let a = {foo:5}
a.id()  // {foo:5}

How can I turn the first function into the second? Is there some hack to do this? I tried working with bind, but it didn't seem to work.

Upvotes: 0

Views: 91

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

You can do it with bind:

let id = a => a;
// ...
let a = {foo:5};
a.id = id.bind(null, a);
a.id(); // {foo:5}

Technically, though, bind returns a new function.


I think you ruled this out, but alternately, of course, just define another arrow:

a.id = _ => id(a);

or a non-arrow

a.id = function() { return id(this); };

...although that one's dependent on how it's called.

Upvotes: 1

user6445533
user6445533

Reputation:

To transform a normal function id into a function that implicitly depends on a receiver (referenced by this) you need to assign an auxiliary function to your prototype:

class Cons {
  constructor(x) { this.foo = x }
  asMethod(f) { return (...args) => f(this, ...args) }
}

const o = new Cons(5);
const id = x => x;

console.log(
  o.asMethod(id) ()
);

This doesn't make much sense though! Your functions would have to expect the receiver as their first argument and hence were quite specific, which is the opposite of generic. That id works in the example is just a coincidence.

Upvotes: 1

Related Questions