[英]return value of anonymous function
我想建立一個墊片。 我有以下墊片,該墊片只能執行一次,並且應該將返回值提供給其他函數。 有點像http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ 。
// WAY 1
matches: function(){
return Element.prototype.matchesSelector
|| Element.prototype.webkitMatchesSelector
|| Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector
|| Element.prototype.oMatchesSelector
|| Element.prototype.matches
|| Element.prototype.webkitMatches
|| Element.prototype.mozMatches
|| Element.prototype.msMatches
|| Element.prototype.oMatches;
}(),
現在,我想通過其他函數使用返回值:
// Uncaught TypeError: Illegal invocation (anonymous function)
if(matches('ul')){
...
}
但是,我無法檢索匹配的返回值,因為它是一個匿名函數。
如果我不立即執行該功能,它將只能工作:
// WAY 2
matches: function(){
return Element.prototype.matchesSelector
|| Element.prototype.webkitMatchesSelector
|| Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector
|| Element.prototype.oMatchesSelector
|| Element.prototype.matches
|| Element.prototype.webkitMatches
|| Element.prototype.mozMatches
|| Element.prototype.msMatches
|| Element.prototype.oMatches;
},
// Now it works, but the method is executed every time.
if(matches('ul')){
...
}
如何使“ WAY 1”起作用?
您使它太復雜了。 只要這樣做:
matches: Element.prototype.matchesSelector
|| Element.prototype.webkitMatchesSelector
|| Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector
|| Element.prototype.oMatchesSelector
|| Element.prototype.matches
|| Element.prototype.webkitMatches
|| Element.prototype.mozMatches
|| Element.prototype.msMatches
|| Element.prototype.oMatches;
如前所述,您有一個名為DOM
的全局對象,使用它可以像執行以下操作:
matches: (DOM._getMatches = function(){
return Element.prototype.matchesSelector
|| Element.prototype.webkitMatchesSelector
|| Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector
|| Element.prototype.oMatchesSelector
|| Element.prototype.matches
|| Element.prototype.webkitMatches
|| Element.prototype.mozMatches
|| Element.prototype.msMatches
|| Element.prototype.oMatches;
})(),
然后在需要時調用_getMatches
:
DOM._getMatches()
如果您的代碼中還有其他全局對象,則可以使用它代替DOM
。
匿名函數是返回另一個函數的函數。
在第一種情況下,您將其調用並將返回的函數存儲在matches
。 然后,您稍后調用該返回的函數。
問題是,該功能的目的是比較存儲在HTML元素this
與您作為參數傳遞一個選擇。
當你打電話matches('ul')
的值, this
是window
(或undefined
嚴格模式)。 那不是HTML元素。
您需要更多類似的東西:
matches.apply(document.getElementById('something_that_might_be_a_list', 'ul');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.