我可以从JavaScript中的绑定函数获取未绑定的函数吗? [英] Can I get an unbound function from a bound function in JavaScript?

查看:87
本文介绍了我可以从JavaScript中的绑定函数获取未绑定的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 来讨论currying和其他技巧。 Function.prototype.bind

更改函数范围似乎非常有用(即值)在某些情况下。

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 value) in certain situations.

看起来你不能改变范围一旦你已经这样做了 bind

function f = obj.method.bind(42); 
function g = obj.method.bind('Hi');

function f2 = f.bind('Hi'); // "this" is still 42

是否可以从绑定函数中检索原始的未绑定函数在什么?

Is it possible to retrieve the original unbound function from a bound function at all?

推荐答案

bind 方法基本上是什么样的(不完全是,因为参数被切片以排除上下文):

What the bind method basically does is something like (not exactly, because arguments are sliced to exclude the context):

function bind(context) {
    var self = this;
    return function() {
        self.apply(context, arguments);
    }
}

所以基本上它正在返回另一个自我调用的函数给定的上下文和参数。如果你再次绑定它,你将绑定这个新创建的函数,就好像 bind 那样实现如下:

So basically it's returning another function which will call itself with the given context and arguments. If you then bind it again, you'll be binding this newly created function, which will be as if bind was implemented like:

 function bind(context) {
    var self = this;
    return function() {
        self.apply(context, arguments);
    }.bind(otherContext);
}

但是因为bind返回的内部函数充当原始上下文的闭包是第一个绑定的( self ),那个将成为你的函数的上下文将被真正执行。

But because the inner function returned by bind acts as a closure where the original context is the one binded first (self), that one will be the context in with your function will be really executed.

这篇关于我可以从JavaScript中的绑定函数获取未绑定的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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