2012-03-22 40 views
3

在jQuery的API文档,该jQuery.proxy函数用法:jQuery.proxy中使用的第三个参数是什么?

jQuery.proxy(function, context) 


功能的功能,其背景将被改变。
上下文应该设置函数的上下文(this)的对象。

jQuery.proxy(context, name) 


上下文到其功能的上下文中应设置的对象。
name其上下文将被更改的函数的名称(应该是上下文对象的属性)。

proxy : function(fn, proxy, thisObject){ 
    if (arguments.length === 2) { 
     if (typeof proxy === "string") { 
     thisObject = fn; 
     fn = thisObject[proxy]; 
     proxy = undefined; 
    } else if (proxy && !jQuery.isFunction(proxy)) { 
     thisObject = proxy; 
     proxy = undefined; 
    } 
} 
    if (!proxy && fn) { 
    proxy = function() { 
    return fn.apply(thisObject || this, arguments); 
    }; 
} 
// So proxy can be declared as an argument 
return proxy; 
} 

但是,当我看着jQuery的源代码,功能代理的。我发现有3个参数声明。

所以我不知道有什么用第三PARAM的,无法理解的代码:(

我写一段代码来测试功能。

var someObj = { somefnc : function() {} }; 
function fnc() { 
    this.somefnc(); 
    console.log(arguments); 
} 
var proxyedFnc = jQuery.proxy(fnc, undefined, someObj, "arg1","arg2"); 
proxyedFnc(); 
//output: [] 

而且我不知道为什么的论点都没有通过到FNC ..

回答

0

下面是源来自jQuery的1.7.2.js,你一定要检查源和API文档之间的相同版本?

// Bind a function to a context, optionally partially applying any 
// arguments. 
proxy: function(fn, context) { 
    if (typeof context === "string") { 
     var 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 
    var args = slice.call(arguments, 2), 
     proxy = function() { 
      return fn.apply(context, args.concat(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 || proxy.guid || jQuery.guid++; 

    return proxy; 
}, 
+0

我的代码来自jQuery 1.5.1。但是,我没有在API doc – ThemeZ 2012-03-22 07:30:55

+0

@ThemeZ中发现任何后来的更改。这并不真正相关,因为您询问的是源代码,而不是API。 – David 2012-03-22 07:36:15

+0

@David你是对的,我只是想知道我在哪里可以找到原来的API文档.. – ThemeZ 2012-03-22 07:41:23

6

xdazz是正确的,最新的1.7.2版本有不同的语法,这也允许多个额外的参数被concated到apply,并传递到代理功能,f.ex:

​var fn = function() { 
    console.log(this.foo, arguments); 
}; 

var obj = { 
    foo: 'bar' 
}; 

$.proxy(fn, obj, 'one', 'two')(); 

运行这段代码将打印bar ["one", "two"]

你会做得到同样的结果:

$.proxy(fn, obj)('one', 'two'); 

我可能阿尔斯o补充说,这些都没有记录在官方的API中,因此在不同版本中,“底层”可能会有所不同。该代码在1.7.2中进行了测试。

+0

我添加了另一种方法来添加似乎在1.5中工作的参数(请参见最后一个示例)。2以及如果这是你所需要的:http://jsfiddle.net/dNYKh/ – David 2012-03-22 07:47:23

+0

非常感谢。它的工作原理 – ThemeZ 2012-03-22 08:02:16

+1

@ThemeZ如果这个答案解决了你的问题,你应该接受它作为最好的答案。 – David 2012-03-22 15:07:37

相关问题