function outside()
{
var myVar = 1 ;
return function (){
alert(myVar);
}
}
var t = outside();
t();
The internal function of a function in js can still access the variables defined in the function after the function is executed. This is called closure (Closure)
The following example is to add onclick to three anchors anchor1, anchor2, and anchor3 event, the expected effect is to click on the anchor point to display the corresponding anchor point ID. In fact, it always displays "My id is anchor4". This is a logical bug caused by the closure. After the function that adds the event is executed, i The value is 4,
ADS.addEvent(window, ' load', function(W3CEvent) {m
for (var i=1 ; i<=3 ; i ) {
var anchor = document.getElementById('anchor' i);
ADS.addEvent(anchor,'click',function() {
alert('My id is anchor' i);
});
}
});
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn