<html>
<head>
<script type="text/javascript"><!--
var context="全局";
var testObj={
context:"初始",
callback:function (str){
//回调函数
alert("callback:我所处的上下文中,context="+this.context+",我被回调的方式:"+str);
},
caller:function(){
callWithClosure(function(param){this.callback(param);});
var temp=this;
callWithClosure(function(param){temp.callback(param);});
}
};
//创建一个对象,作为测试回调函数的上下文
testObj.context="已设置";
function testCall(){
//callMethod(testObj.callback);
testObj.caller();
//callWithClosure(function(param){testObj.callback(param);});
//callObjMethod(testObj,testObj.callback);
}
function callObjMethod(obj,method){method.call(obj,"指定显式对象上下文回调"); }
function callMethod(method){ method("通过默认上下文回调"); }
function callWithClosure(method){ method("通过Closure保持上下文回调"); }
function callback(str){ alert("callback:我是定义在外部的全局函数。"); }
// --></script>
</head>
<body>
<a href="javascript:void(0)">调用测试</a>
</body>
</html>
8、什么是Closure
Two one sentence summaries:
a closure is the local variables for a function - kept alive after the function has returned,
or
a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)
您可能感兴趣的文章: