简体   繁体   中英

How do you know which parameters to set for a javascript function?

Coming from Java, Javascript can be really frustrating.

I'm hoping someone can put this into simple terms for me.

I'm struggling to understand how Javascript programmers know which parameters to pass for a method they're calling - especially when that method is being called as a callback (which in my eyes seems like an added level of complexity).

For example , take the function addEventListener . In this function, a typical use looks like

myDOMItem.addEventListener("click", function(e){...}, false);

In the documentation for this function (hyperlinked to name above) I don't see any mention of this option. Whereas in Java you can easily know if your parameters match the type especially with a good IDE, in Javascript it seems like a huge guessing game or requires serious in-depth knowledge of each function.

How do Javascript programmers do it?

The documentation you linked to does show the form in your example:

target.addEventListener(type, listener[, useCapture]);

The type parameter is the string "click" , listener is the function object, and useCapture is false .

We either remember things, or get a good IDE that actually has decent support. Everyone has their favorite, so I won't presume to say that there is a "best" IDE. In my humble opinion, Webstorm is one of the best.

In the Mozilla documentation is clearly stated that the function takes four arguments:

  • string ( type )
  • function/implementer of EventListener ( listener )
  • boolean ( useCapture ).
  • boolean ( wantsUntrusted ). Available only for Mozilla/Gecko browsers.

As you can see from the signature, last two parameters are optional and therefore wrapped in brackets:

target.addEventListener(type, listener[, useCapture, wantsUntrusted ]);

To effectively code in JavaScript, you need to organize development environment just like for Java. Java world provides almost endless number of tools for different tasks (UI development, server-side development etc.). The same situation with JavaScript. I would like to avoid ads for IDEs/Editors. Therefore I advise you to use search to find the right tools for your JavaScript-related dev stack.

PS Personal opinion. I also came to JavaScript from Java. From my experience, the main problem for Java developers is not the lack of tools but the lack of strict code structure. Since Java gives powerful OOP experience, probably it will be more easily for you to start working with JavaScript in OOP terms. Good development stack for OOP-like JavaScript is provided by the open source project Google Closure Tools.

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