2013-06-30 82 views
0
function shortUrl() { 
$['post']('http://tinyurl.com/api-create.php?url=http://json-tinyurl.appspot.com/', function (a) { 

}); 
}; 

我想使这个函数成为一个var,所以我可以在脚本中使用shortUrl Anywhere。像将函数声明为变量

var shortaddress = shortUrl(); 

我想在下一个函数中使用结果。

+2

欢迎来到** async **的美妙世界!你不能那样做。 – SLaks

+1

'shortUrl' * *已经是一个变量。我不太确定你试图达到什么目的。 –

+0

以及我想在下一个函数中使用shorturl。 – Johan

回答

7
function shortUrl() {...} 

相当于

var shortUrl = function() {...}; 

所以,这已经是一个变量。

+0

请使用我的脚本来描述一点javascript to new new:( – Johan

+4

* *不等于,虽然它是相似的1)函数声明被挂起, 2)第二种形式没有功能名称; 3)函数声明可能* only *作为顶级语句出现(即它*不能*出现在'if')或“非浏览器行为”结果中,只需要注意一点小问题。 – user2246674

1

函数已经是一个变量,所以你可以这样使用它。例如:

function foo() { 
    // ... 
}; 

或多或少相同

var foo = function() { 
    // ... 
}; 

基本上,如果你删除括号和参数(foo代替foo()),则可以使用任何功能作为一个正常的变量。

因此可以例如将其分配给其他变量,就像你通常会:

var bar = foo; // note: no parentheses 
bar();   // is now the same as foo() 

或者你可以把它作为一个参数传递给另外一个函数:

function callFunc(func) { 
    func(); // call the variable 'func' as a function 
} 

callFunc(foo); // pass the foo function to another function 
+0

dint未理解最后部分... function callFoo(func){func();} //作为函数调用变量'func' } callFunc(foo); //将foo函数传递给另一个函数 –

0

如果你想在任何地方使用shortUrl函数,它必须在全局范围内声明。然后,该变量成为Window对象的属性。例如,下面的变量

<script type="text/javascript"> 
    var i = 123; 
    function showA(){ alert('it'); window.j = 456; } 
    var showB = function() { alert('works'); var k = 789; this.L = 10; } 
</script> 

直接在Window对象申报等都成为它的属性。因此,现在可以通过任何脚本轻松访问它们。举例而言,所有下面的命令工作:在JavaScript

<script type="text/javascript"> 
    alert(i); alert(window.i); 
    showA(); window.showA(); 
    showB(); window.showB(); 
    alert(j); alert(window.j); 
    alert(new showB().L); // here the function was called as constructor to create a new object 
</script> 

函数是对象,所以他们可以在自己持有的属性。
在上面的示例中,您可以将k变量视为私有财产,将L变量视为showB对象(或函数)的公有财产。另一个例子:如果你在页面中包含jQuery库,jQuery通常会将自己公开为window.jQuerywindow.$对象。通常建议使用全局变量非常小心谨慎地防止可能的冲突。