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

本小妞迷上赌 提交于 2019-12-13 13:18:01

问题


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.



来源:https://stackoverflow.com/questions/39191045/better-way-to-check-if-function-is-already-bound-in-plain-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!