Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a function was called with `.call` or `.apply`?

I created this function so that I could chain methods together:

export default function bindable(fn) {
    return function boundFn(...args) {
        return this === undefined ? fn(...args) : fn(this, ...args);
    }
}

It works with the bind operator. For example, you can define a new function like,

 export const flatten = bindable(arrayOfArrays => Array.prototype.concat(...arrayOfArrays));

And then use it like this:

[[1,2,3],[4,5,6]]::flatten()

Or like this:

flatten([[1,2,3],[4,5,6]])

Babel REPL

This worked great at first until I realized that if I use it like in the second scenario, but import the helper method as a module, it breaks the context!

 import * as Arr from './array-helper-methods';
 Arr.flatten([1,2,3]); // `this` is now `Arr`

So my question is: is there any way that I can reliably detect if a function is called with the bind operator?

like image 720
mpen Avatar asked Jan 31 '26 21:01

mpen


1 Answers

That's a large and yet unsolved problem of the bind operator. But no, it only works for methods. You just should provide two versions of your functions if you want to support both styles.

Doing it dynamically is hard. No, you cannot detect whether the function was called using (), as a method, was bound, with call or apply etc. And you really shouldn't be able to anyway.

For your case, I'd choose

function bindable(fn, isContext) {
    return function boundFn(...args) {
        return isContext(this) ? fn(this, ...args) : fn(...args);
    }
}
export default bindable(bindable, f => typeof f == "function");

Then you can use bindable(flatten, Array.isArray) or flatten::bindable(Array.isArray) for flatten. For more complicated cases, you can also incorporate the arity of the function, i.e. whether fn.length + 1 == args.length.

like image 107
Bergi Avatar answered Feb 03 '26 11:02

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!