Home > Web Front-end > JS Tutorial > An example of js closure_javascript skills

An example of js closure_javascript skills

WBOY
Release: 2016-05-16 18:58:37
Original
1018 people have browsed it
Copy code The code is as follows:

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,
Copy code The code is as follows:

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);
});
}
});
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template