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"
Is this a reliable check ?
Are there more ways to find if function is already bound ?
*NOTE: Not interested in older browsers (ex : <ie10
)
You can check for a function using the typeof keyword, which will return "function" if given the name of any JavaScript function.
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.
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.
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.
Is this a reliable check?
No. It only works since ES6, but it also can be fooled since ES6 because .name
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With