0

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.

2
  • Are you asking how to put a function on every object? Don't do that. Commented May 12, 2017 at 16:01
  • 2
    This feels like an X/Y problem. You need to do X, think Y is the way to do it, and have asked about Y. What's X? Commented May 12, 2017 at 16:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.