Reputation: 15006
I'm trying to understand this javascript-code:
onMouseMoved = (function(_this) {
return function(event) {
dx = (event.pageX/3) / window.innerWidth;
dy = (event.pageY/3) / window.innerHeight;
return tr = Math.atan2(hy, hx);
};
})(this);
window.addEventListener('mousemove', onMouseMoved, false);
Why does the outer function return a function and where does the event-variable come from?
Upvotes: 1
Views: 65
Reputation: 318192
The first function is an Immediately-Invoked Function Expression (IIFE) it executes right away and returns another function that is set as the callback for the event handler.
It could also be written like this
window.addEventListener('mousemove', onMouseMoved, false);
function onMouseMoved(event) {
dx = (event.pageX/3) / window.innerWidth;
dy = (event.pageY/3) / window.innerHeight;
return tr = Math.atan2(hy, hx);
};
or this
window.addEventListener('mousemove', function(event) {
dx = (event.pageX/3) / window.innerWidth;
dy = (event.pageY/3) / window.innerHeight;
return tr = Math.atan2(hy, hx);
}, false);
This would be exactly the same, but we wouldn't have the value of _this
, which seems like the reason for the IIFE, locking in the outer value of this
, but that function argument is never used, so it doesn't seem like it's neccessary here.
So the event argument is coming from the native addEventListener
For a thorough explanation as to how the IIFE works, see this
Why do you need to invoke an anonymous function on the same line?
Upvotes: 1
Reputation: 943571
Why does the outer function return a function
Because:
(a) It has a return statement in front of a function expression
and
(b) The returned function is used as an argument to a function that expects that argument be a function
where does the event-variable come from
From the native browser code that implements the event listener routines (according to the specification for addEventListener
)
Upvotes: 1