Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to check if function is already bound in plain JavaScript ?

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)

like image 944
Mihai B. Avatar asked Aug 28 '16 12:08

Mihai B.


People also ask

How do you check if a function has been called in JavaScript?

You can check for a function using the typeof keyword, which will return "function" if given the name of any JavaScript function.

How do you check if a function has been executed?

You can drop the == true since they both return booleans. If this condition if (function1() && function2() ){ is true, it means that these functions was executed and returned true. just be aware of that if the first function doesn't return true or the second won't be executed.

What is bind() JavaScript?

bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

How do you call a bound function in JavaScript?

You can use call() / apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful.


1 Answers

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.

like image 195
Bergi Avatar answered Oct 12 '22 19:10

Bergi