teimdw
Last Updated: February 25, 2016
·
834
· bahlor

Passing over variables to anonymous functions

Its actually pretty easy but still some people seem to not know it. So I will give you an example:

function hover(e) {
    document.getElementById('block').innerHTML = (function (_this, event) {
        return (event.pageX-_this.offsetLeft)+','+(event.pageY-_this.offsetTop);
     })(this, e);
 }

 document.getElementById('block').addEventListener('mousemove', hover, true);

The function will invoke itself due to its definition

(function(arg1,arg2) { /* logic */ })(passedArg1, passedArg2);

And this is it. This is especially useful when you need to pass over this to an anonymous function. Hope this might help someone.

jsFiddle Demo

1 Response
Add your response

7910

Thanks for the tip, but don't you think that your example doesn't show the case you mentioned - passing this to an anonymous function.
Your code works without anon. function:

document.getElementById('block').innerHTML = (e.pageX-this.offsetLeft)+','+(e.pageY-this.offsetTop);

over 1 year ago ·