2013-02-20 35 views
8

我相信他们都允许你控制'this'的价值,但除此之外,我有点不清楚,而Google/SO迄今为止帮助不大。任何澄清赞赏。我发现这一点,但我怀疑它道出了原委:

“当我第一次了解jQuery的代理()方法,我认为这是 有点傻,毕竟,使用Javascript已经有但是,一旦你意识到jQuery的proxy()方法允许你轻松地绑定()和解除绑定()事件 处理程序,无论上下文,它变得很明显只是有多强大 这种方法是。

+0

Google-fu:JavaScript执行上下文有用的搜索条件。 – cmbuckley 2013-02-20 23:13:34

+2

很多jQuery的东西都是毫无意义的。许多人认为使用'$(this).attr('id')'而不是'this.id'是即时的。我没有看过'$ .proxy',但它完全可能是一样的:冗余和毫无意义。 – 2013-02-20 23:14:33

+0

@Kolink当你编写一个函数返回一个返回应用的函数时,它就是这样。几乎每个图书馆都有这种方法。 – epascarello 2013-02-20 23:23:12

回答

11

调用的对象/应用是单次调用。 $ .proxy创建一个新的功能永久绑定到的东西:

fn.call(foo); //call once 

var otherFn = $.proxy(fn, foo); // you can call it again later 

var otherOtherFn = fn.bind(foo); // ES5 standard way 

由于简化(非常简化),$.proxy正在创造一个新的函数调用call

$.proxy = function(fn, newThis) { 
    return function() { 
     fn.call(newThis); 
    } 
} 

它类似于ES5的Function.prototype.bind

5

看看jQuery源代码:

proxy: function(fn, context) { 
    var tmp, args, proxy; 

    if (typeof context === "string") { 
     tmp = fn[ context ]; 
     context = fn; 
     fn = tmp; 
    } 

    // Quick check to determine if target is callable, in the spec 
    // this throws a TypeError, but we will just return undefined. 
    if (!jQuery.isFunction(fn)) { 
     return undefined; 
    } 

    // Simulated bind 
    args = core_slice.call(arguments, 2); 
    proxy = function() { 
     return fn.apply(context || this, args.concat(core_slice.call(arguments))); 
    }; 

    // Set the guid of unique handler to the same of original handler, so it can be removed 
    proxy.guid = fn.guid = fn.guid || jQuery.guid++; 

    return proxy; 
}, 

如果删除缓存代码,使之更短一点,你基本上得到.apply()(我想我正确地转换切片码):

proxy: function(fn, context) { 
    var args = [].slice.call(arguments, 2); 

    return function() { 
     return fn.apply(context || this, args.concat([].slice.call(arguments))); 
    }; 
} 
1

$.proxy你可以在一个函数调用它返回的函数总会有一个特定的上下文。这意味着,如果你跑

$.proxy(function() {console.log(this.val)}, {val: 1}).call({val: 2}); 

这将登录1因为函数总是绑定到最初传递给proxy