更好的方法来检查功能是否已经绑定在普通的JavaScript? [英] Better way to check if function is already bound in plain JavaScript ?

查看:115
本文介绍了更好的方法来检查功能是否已经绑定在普通的JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于一种情况,我想知道是否已经绑定了一个函数,以便在函数调用时使用 call 应用与不同的上下文。

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


var ref = myfn.bind(null);

我在Firefox和Chrome控制台中检查了函数对象,唯一的区别是绑定版本名称的前缀为界限。

 > myfn.name 
> myfn

> ref.name
> bound myfn




  1. 这是可靠的检查吗?

  2. 是否有更多方法可以查找
    函数是否已经绑定?



  3. *注意:对旧浏览器不感兴趣(例如:< 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"
    

    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)

    解决方案

    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.

    这篇关于更好的方法来检查功能是否已经绑定在普通的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆