匿名函数的返回值

时间:2014-02-14 09:55:39

标签: javascript

我想建立一个垫片。我有以下垫片,只能执行一次,并且应该将返回值提供给其他函数。这有点像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”工作?

3 个答案:

答案 0 :(得分:2)

你太复杂了。就这样做:

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;

答案 1 :(得分:1)

正如您所提到的,您有一个名为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

答案 2 :(得分:0)

匿名函数是一个返回另一个函数的函数。

在第一种情况下,您调用它并将返回的函数存储在matches上。然后你稍后调用返回的函数。

问题在于该函数的目的是将this中存储的HTML元素与作为参数传递的选择器进行比较。

当您致电matches('ul')时,this的值为window(或严格模式下为undefined)。这不是一个HTML元素。

你需要更像的东西:

matches.apply(document.getElementById('something_that_might_be_a_list', 'ul');
相关问题