简体   繁体   English

如何摆脱这种自调用功能?

[英]How can I get rid of this self-calling function?

I found this awesome snippet on the internet: 我在互联网上找到了这个很棒的片段:

function f(a,b,c,d){for(d?d=b.toUpperCase():b=4;!d&&b--;d=(d=d.replace(/-(.)/g,f))in(new Image).style&&d)d=[['Moz-','Webkit-','Ms-','O-'][b]]+a;return d}

It takes the name of a css property, and adds the correct vendor prefix automatically. 它使用css属性的名称,并自动添加正确的供应商前缀。

I golfed it a bit to make it smaller: 我打了一些球以使其更小:

function f(a,b,c){for(c?c=b.toUpperCase():b=4;!c&&b--;c=(c=c.replace(/-(.)/,f))in(new Image).style&&c)c=["Moz-","Webkit-","Ms-","O-"][b]+a;return c}

I would like to submit it to 140bytes, but this function calls itself, which means that it pollutes the global namespace with a variable (f) 我想将其提交为140bytes,但是此函数会自行调用,这意味着它将使用变量(f)污染全局名称空间。

How can I change it so it doesn't call itself? 我如何更改它以使其自身不被调用?

Here is a jsfiddle: http://jsfiddle.net/vCkew/ 这是一个jsfiddle: http : //jsfiddle.net/vCkew/

Use some scoping: 使用一些作用域:

var myFunction = function(a, b, c) {
    var f = function(a, b, c) {
        for (c ? c = b.toUpperCase() : b = 4; !c && b--; c = (c = c.replace(/-(.)/, f)) in (new Image).style && c)
        c = ["Moz-", "Webkit-", "Ms-", "O-"][b] + a;
        return c;
    }
    return f(a, b, c);
}

http://jsfiddle.net/maniator/vCkew/3/ http://jsfiddle.net/maniator/vCkew/3/

You can use the arguments keyword to get the function: 您可以使用arguments关键字来获取函数:

function(a,b,c){for(c?c=b.toUpperCase():b=4;!c&&b--;c=(c=c.replace(/-(.)/,arguments.callee))in(new Image).style&&c)c=["Moz-","Webkit-","Ms-","O-"][b]+a;return c}

To make it work in your jsfiddle: 要使其在您的jsfiddle中起作用:

document.write((function(a,b,c){for(c?c=b.toUpperCase():b=4;!c&&b--;c=(c=c.replace(/-(.)/,arguments.callee))in(new Image).style&&c)c=["Moz-","Webkit-","Ms-","O-"][b]+a;return c})('transition'));​

NOTE: This does actually answer your question to make the function not call itself but it does remove the function from the global namespace. 注意:实际上,这确实回答了您的问题,以使函数不调用自身,但确实从全局名称空间中删除了该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM