2012-03-22 38 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

相關問題