Better way to check if function is already bound i

2019-06-22 10:18发布

问题:

I'm in a situation where I would want to know if a function is already bound in order to set a warning message when that function is invoked with call or apply with a different context.

function myfn (){ }
/* or */
var myfn = function () {}


var ref = myfn.bind(null);

I checked the function object in Firefox and Chrome console and the only difference I found is that the bound version has the name prefixed with bound.

> myfn.name
> "myfn"

> ref.name
> "bound myfn"
  1. Is this a reliable check ?

  2. Are there more ways to find if function is already bound ?

*NOTE: Not interested in older browsers (ex : <ie10)

回答1:

Is this a reliable check?

No. It only works since ES6, but it also can be fooled since ES6 because .names are writable now.

Are there more ways to find if function is already bound?

Bound functions do not have a .prototype property, but notice that there are others that share this quality, e.g. all arrow functions.