更好的方法来检查功能是否已经绑定在普通的JavaScript? [英] Better way to check if function is already bound in plain JavaScript ?
问题描述
我处于一种情况,我想知道是否已经绑定了一个函数,以便在函数调用时使用 call
或应用
与不同的上下文。
function myfn(){}
/ *或* /
var myfn = function(){ }
var ref = myfn.bind(null);
我在Firefox和Chrome控制台中检查了函数对象,唯一的区别是绑定版本名称的前缀为界限。
> myfn.name
> myfn
> ref.name
> bound myfn
-
这是可靠的检查吗?
-
是否有更多方法可以查找
函数是否已经绑定? Is this a reliable check ?
Are there more ways to find if function is already bound ?
*注意:对旧浏览器不感兴趣(例如:< ie10
)
没有。它只适用于ES6以来的版本,但它也可能因为ES6而被愚弄,因为 .name
s现在是可写的。
有没有更多的方法来查找函数是否已经绑定?
绑定函数没有 .prototype
属性,但请注意,还有其他人可以共享此质量,例如所有箭头功能。
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"
*NOTE: Not interested in older browsers (ex : <ie10
)
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.
这篇关于更好的方法来检查功能是否已经绑定在普通的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!