function shortUrl() {
$['post']('http://tinyurl.com/api-create.php?url=http://json-tinyurl.appspot.com/', function (a) {
});
};
我想使这个函数成为一个var,所以我可以在脚本中使用shortUrl Anywhere。像将函数声明为变量
var shortaddress = shortUrl();
我想在下一个函数中使用结果。
function shortUrl() {
$['post']('http://tinyurl.com/api-create.php?url=http://json-tinyurl.appspot.com/', function (a) {
});
};
我想使这个函数成为一个var,所以我可以在脚本中使用shortUrl Anywhere。像将函数声明为变量
var shortaddress = shortUrl();
我想在下一个函数中使用结果。
function shortUrl() {...}
相当于
var shortUrl = function() {...};
所以,这已经是一个变量。
请使用我的脚本来描述一点javascript to new new:( – Johan
* *不等于,虽然它是相似的1)函数声明被挂起, 2)第二种形式没有功能名称; 3)函数声明可能* only *作为顶级语句出现(即它*不能*出现在'if')或“非浏览器行为”结果中,只需要注意一点小问题。 – user2246674
函数已经是一个变量,所以你可以这样使用它。例如:
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
dint未理解最后部分... function callFoo(func){func();} //作为函数调用变量'func' } callFunc(foo); //将foo函数传递给另一个函数 –
如果你想在任何地方使用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.jQuery
或window.$
对象。通常建议使用全局变量非常小心谨慎地防止可能的冲突。
欢迎来到** async **的美妙世界!你不能那样做。 – SLaks
'shortUrl' * *已经是一个变量。我不太确定你试图达到什么目的。 –
以及我想在下一个函数中使用shorturl。 – Johan