简体   繁体   中英

Newbie question about document.addEventListener('mousemove', function (e) {

Okay:

document.addEventListener('mousemove', function (e) {...code...}, false);

Recently I realized that I could greatly enhance my interaction with a few websites by way of Chrome extensions to reorder and rewrite the website to suit my needs.

So, I've been trying to get a grasp of chrome extensions, javascript, css, dom, jquery and HTML. It is a huge subject and I am woefully unfamiliar with web technologies.

Can someone please explain what 'function(e){...code...}' is in this context?

It is an inline function without a name? So, unlike other languages, instead of creating a function with a name and then calling it when needed, this statement hooks the mousemove with an unnamed function?

I suppose it is a stupid question to ask what the benefit is to having an inlined unnamed function is?

function (e) {...code...} is a reference to an anonymous function to run on the occurence of the mousemove event. The e parameter is the event Object that is sent with the event itself.

So basically you say: everytime someone moves his/her mouse around somewhere in the DOM Object document , execute the function using the event Object I give you in the parameter of that function.

You could've also used (and this is sometimes advised for readability and clarity):

function mousemover(e){ ... }
document.addEventListener('mousemove', mousemover, false);

That is also the preferred way if you later on decide to remove the eventlistener ( removeEventListener ).

An inline anonymous function is sometimes called a lambda function . You can read about it in this SO Question .

As per request in the comments: in javascript functions are first class objects . Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures (quoted from this wikipedia page ). Also read more on Douglas Crockfords page .

They are called anonymous functions.

You can read a little more about them here:

http://en.wikipedia.org/wiki/Anonymous_function#JavaScript

Inlined (anonymous) functions are just a style thing, allowing for shorter code. They can also avoid polluting the namespace by introducing unneeded names into the current scope.

However in this particular case there is a downside in that it's impossible to remove a specific event listener if it was added anonymously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM