我想構建一個墊片。我有以下墊片,它只能執行一次,並應將返回的值賦予其他函數。這有點像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;
}(),
現在我想等功能,使用返回值:
但我不能檢索匹配的返回值,因爲它是個匿名函數。
它只會工作,如果我不excecute功能一次:
// 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」的工作?
有什麼不清楚的,特別是關於你的'if(matches('ul')){':你如何處理用正確的上下文調用函數? –
我在對象DomUtil {matches:function()); ...}中包裝「匹配」功能。在dom被加載後調用if(DomUtil.matches('ul'))在點擊處理程序中執行。但是,如果我使用WAY 2而不是WAY 1,它纔有效。然而WAY 2每次調用函數時都會執行該函數,這是沒用的,因爲執行後返回的值沒有差異。因此,我想讓「方式1」工作。 – nimo23