Can I get an unbound function from a bound function in JavaScript?

前端 未结 3 444
醉话见心
醉话见心 2020-12-25 12:59

I\'m getting my head wrapped about currying and other techniques using Function.prototype.bind.
It seems extremely useful to change function scope (i.e., this

3条回答
  •  青春惊慌失措
    2020-12-25 13:27

    This would actually solve you issue

    const bind = Function.prototype.bind;
    Object.defineProperty(Function.prototype, 'bind', {
        value: function () {
            const result = bind.apply(this, arguments);
            result.source = (this.source || this);
            return result;
        }
    });
    

    Now you can get the source property to get the original function. This could cause other issues, but performance does not seem to be one of them, https://jsperf.com/bind-override/1

    Both IE, Edge, Firefox and Chrome seems to get the same result, sometimes the normal version is faster and sometimes the overridden is faster.

提交回复
热议问题