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.
Written by Christian Weber
Related protips
1 Response
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);
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside