( ! ) Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in D:\www\up\js\function.php on line 14
Call Stack
#TimeMemoryFunctionLocation
10.0000355960{main}( )...\function.php:0

( ! ) Warning: include(http://pub.houheaven.com/Nav02/Nav_deep2.htm): failed to open stream: no suitable wrapper could be found in D:\www\up\js\function.php on line 14
Call Stack
#TimeMemoryFunctionLocation
10.0000355960{main}( )...\function.php:0

( ! ) Warning: include(): Failed opening 'http://pub.houheaven.com/Nav02/Nav_deep2.htm' for inclusion (include_path='.;C:\php\pear') in D:\www\up\js\function.php on line 14
Call Stack
#TimeMemoryFunctionLocation
10.0000355960{main}( )...\function.php:0

信息:原创2014-09-070 次阅读0 个评论

标签:后天堂向上,网站制作,自学教程,网站技术,javascript,javascript函数

普通函数

函数,是能够实现特定功能的代码段,一般分为内置函数和外部函数(用户自定义函数)。

为了能够被调用,普通函数必须要有函数名,但是参数与返回值是可选的。

创建

function greet()

{

alert("hello");

}



匿名函数

匿名函数,就是没有名字的函数。


①. 创建匿名函数

function()

{

// 没有函数名,无法被调用 

alert("hello");

}

 

var greet=function()

{

// 匿名函数赋值给一个变量,实现被调用 

alert("hello");

}


②. 自动执行的匿名函数

格式:(匿名函数)();

说明:第一个小括号放匿名函数本身,第二个小括号功能是执行匿名函数。

//不传递参数 

(function(){

alert("hello");

})();

 

//传递参数 

(function(param){

alert(param);

})(param);



闭包

闭包,指的是函数里面的匿名函数,它里面的 this 指向 window。

闭包实现局部变量累加

function grow()

{

var age=12;

return function(){ return ++age; };

}

 // 整体调用

alert(grow()());// 输出 13

alert(grow()());// 输出 13

alert(grow()());// 输出 13

 

fun=grow();// 闭包调用

alert(fun());// 输出 13

alert(fun());// 输出 14

alert(fun());// 输出 15

说明,闭包中返回的变量不会被立即销毁,所以,上述功能能够正常实现,但是也容易造成内存占用与浪费。

上述功能也可以使用普通函数操作全局变量来实现,但是全局变量操作不当容易造成全局环境污染。

显示框架
top