日期:2014-05-16 浏览次数:20414 次
?
闭包说白了就是封装的意思..为了隐藏方法内部的实现细节..
?
下面一段代码说明闭包的使用:
?
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>闭包的实现方式</title> <script type="text/javascript"> var commVar = 100; //闭包的实现方式一; //Ecmscript中所谓的闭包,函数能使用函数外定义的变量并且不需要传递参数; function showMessage(){ alert(commVar); } showMessage(); //闭包的实现方式二; //函数addNum()包括函数doAdd()闭包,内部函数是一个闭包,因为它将获取外部的参数num1和num2以及全局变量的值. function addNum(num1,num2){ function doNum(){ return commVar+num1+num2; } return doNum(); } alert(addNum(10,10)); //闭包实现方式三; function countNumFunction(num1){ return function(num2){ return num1 + num2; } } //引用闭包函数; var res = countNumFunction(10); alert(res(15)); var sayHello = "hello "; //闭包实现方式四; (function(num1){ var commName = "world"; (function(){ alert(sayHello+commName+":"+num1); })(); })("500"); //闭包实现方式五; function setDivStyle(message,time){ setTimeout(function(){ var divObj = document.createElement("div"); var textObj = document.createTextNode(message); //把textObj对象追加到divObj中; divObj.appendChild(textObj); divObj.style.border="1px solid red"; divObj.style.background = "green"; document.body.appendChild(divObj); },time); } setDivStyle("javascript 实例!!",3000) setTimeout(function(){ var pobj = document.getElementById("pid"); pobj.style.display = "none"; },3000); </script> </head> <body> <p id="pid">Hello World!!!</p> </body> </html>
?