2013-06-30 81 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.$對象。通常建議使用全局變量非常小心謹慎地防止可能的衝突。