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);
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#