JavaScript Closure Memory Leak by Circular Reference Example

Code 1
function fn(elem, a, b) {
elem.onclick=function() {
a,b
}
}

Code 2
function fn(elem, a, b) {
elem.onclick=(function(a,b) {
return function() {
a,b
}
})(a,b)
}

Code 1 is the common way we write JS function.
Code 2 is an ugly way but do the same thing.
But Code 1 will cause memory leak and Code 2 does not.
The memory leak so called circular reference.
The closure is a beautiful structure in JavaScript but easily cause memory leak if written by not experienced developer.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University