Home  >  Article  >  Web Front-end  >  JavaScript explained from a Java developer's perspective

JavaScript explained from a Java developer's perspective

伊谢尔伦
伊谢尔伦Original
2016-11-23 10:03:331374browse

We can’t explain all the details of JavaScript in one blog post. If you're involved in web application development at one level or another, our Java Tools and Technology Scope report reveals that the majority (71%) of Java developers fall into this category, but you're just having trouble with JavaScript. hinder.

There is no doubt that you already know Java and JavaScript. No matter how similar they are named, they do not share much in common with each other. Java's static typing, straightforward syntax, and verbosity are vastly different from JavaScript's dynamics, lack of consistency, and weirdness.

 However, JavaScript is the programming language of the web, and has recently gained considerable attention on the server side due to the development of Node.js and the JVM's own Nashorn JavaScript engine.

In this article, I don’t want to just talk about the good and bad aspects of JavaScript, or repeat the countless JavaScript tutorials that anyone can find for free. I want to list some technical points that are helpful in understanding JavaScript as a language, and understand it from a close horse perspective.

We will include the following language-level technical points in this article:

Universality of JavaScript

Functional programming issues in JavaScript

Different inheritance from Java

In addition, you will find some recommendations for tools that are not available without these tools , you don't want to start a JavaScript project, contains tools for code quality analysis and testing frameworks for build systems.

Advantages

Write it once and run it almost everywhere!

There is no doubt that JavaScript is the web programming language, the compilation target of many other languages, and the ultimate way to prove that sometimes people just want to have more free time. Still, that's not a bad thing. Every computer capable of browsing modern websites is equipped with a powerful and usable JavaScript engine. Best of all, JavaScript code can be run on the backend.

 Nashorn, a lightweight and high-performance JavaScript runtime built into our favorite JVM, is fully capable of interpreting JavaScript scripts and can also interpret JavaScript scripts with Java code in the project.

Given the freedom available to every computer running it, JavaScript becomes the perfect continuation of the Java experience.

 Functional programming: First-class citizens are functions, not recursion

  Functions in JavaScript are first-class citizens. They are values ​​that can be stored in variables, passed to other functions, and executed at the appropriate time.

 This opens the door to the world of functional programming, which is the perfect way to structure JavaScript programming.

Note that an object in JavaScript is a mapping of anything. Every attribute of the object is in the same mapping: functions, properties, constructors; variability brings greater hidden dangers, and With Java, you can at least ensure that method and field structures are stable to some extent.

 This, in turn, makes functional programming more advantageous: involving small, understandable functions and immutable data structures is the way to run in JavaScript.

 This is not without basis. The following is an example of defining a reduce function in JavaScript, from the book "Eloquent JavaScript".

function forEach(array, action) {
for (var i = 0; i < array.length; i++) {
action(array[i]); //apply action to every element of the arra.
}
}
  
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element); // and here we apply function passed as ‘combine’ parameter to ‘base’ and ‘element’
});
return base;
}
  
function add(a, b) { // btw, this is how you define a function in JavaScript
return a + b;
}
  
function sum(numbers) {
return reduce(add, 0, numbers);
}

Note: We are not using the recursive version of reduce here. JavaScript does not feature tail calls [Note 1], which means that the recursive version of each function will use the depth of the stack. Like Java, if you recurse too deep, the program will crash.

 Inheritance: Just like the real world

 JavaScript inheritance is based on prototypes. That is, you do not extend the type of other types, but in fact, the instances you have inherit functionality from other instances.

Imagine that object A is like a map, which we just mentioned a little bit, but from a different perspective, and then another map-like object B inherits everything from A.

This means that B can access all parts of A: A’s methods, fields, etc.

In practice, I've never seen anyone actually use simple prototype-based inheritance. Usually when someone needs inheritance, he just constructs the class, so you can use all the broad skills and working patterns of class-based inheritance.
——Rene Saarsoo, XRebel front-end engineer

I’m not sure what Java developers should take away from this, but beware of differences in inheritance methods, pay special attention to parent objects, and not accidentally change the behavior of the entire program.

  Things to avoid at all times

Listing unreliable JavaScript design decisions is easier than you think. The most obvious place to avoid in a JavaScript program is the declaration of global variables.

 Note that in JavaScript, whenever you define a variable without using the var keyword, the defined variables are pushed to the top of the scope in which they are defined. This means that every variable defined in this way will run to the top of the global scope, causing conflicts and unexpected headaches for you and your colleagues.

  Strict mode can be turned on. Just write "use strict" at the top of your script file and an inadvertently written global variable declaration will show an error.

Another important difference between JavaScript and Java is that the former is a dynamically typed language, and the essence is that everything can be of any type. This is obvious and cannot be emphasized enough: do not reuse the same variable for different types of values.

  The tracking was originally a string type variable, but now it has become a floating point number or function, trust me!

Also, I don’t want to get too deep into the discussion of types and booleans, but be wary of implicit type conversions that the JavaScript engine throws at you.

 Tips to Get the Job Done

 As I mentioned above, when programming you need to pay more attention to the syntax and quirks of the language than just know it. Projects rarely fail due to language deficiencies, more often they are related to deficiencies in the overall project framework. Here are some tools to help you deliver your projects.

 Static Code Analysis

Most projects are different, and their complexity and requirements lead to a lot of details on how you go about your code base. Nonetheless, there is a consistent goal everywhere, and that is code quality.

 Yes, code quality, the most important job for any developer is delivery. But don't compromise on quality, and don't be reluctant to share the code you submit with colleagues because you don't feel confident in it.

Fortunately, JavaScript has a decent solution - JSHint. JSHint is a static analysis tool tailored for JavaScript, similar to FindBug for Java code. JSHint can run through your code base and highlight suspicious or problematic areas that, even if you don't create bugs right away, may become difficult to maintain in the future. Supporting it in your project is fairly simple. Do yourself a favor - if you're writing JavaScript code, use JSHint to make it safer and less awkward.

  REPL

  REPL stands for "Read-Eval-Print Loop" [Note 2], which is a powerful tool for many dynamic languages. If you have seen Scala or Groovy, you will definitely be able to understand this concept.

 One way to activate JavaScript REPL is to open the browser's console, which produces an interface for evaluating JavaScript code.

JavaScript explained from a Java developers perspective

Another more convenient tool is jjs, which is bundled with JDK1.8.

JavaScript explained from a Java developers perspective

It is a command line tool that allows you to access the Nashorn JavaScript engine in the JDK, fully capable of executing even the most rigorous JavaScript scripts.

 Testing

 With any project, you want to run some tests. Testing is especially important for dynamically typed languages, and it is best to choose a testing framework. I recommend Jasmine, which is a behavior-driven development framework for testing JavaScript.

JavaScript explained from a Java developers perspective

In Jasmine, you use describe to describe your test suite, which blocks access to the code you want to test. After the code under test is completed, you expect some results.

Obviously this is not meant to be a tutorial, but I wanted to give you a glimpse of how elegant JavaScript code can look. Jasmine is one of the best practices for JavaScript projects, and we privately apply it to the ZeroTurnaround project in product development, especially for the JavaScript-rich interactive analyzer XRebel that runs continuously.

 Build Tools

Finally, the more important thing your project will need is a build tool. If you're using JavaScript in a Java project, make sure you can avoid the Java build tools, and that's almost enough. However, for independent JavaScript projects, there is no need to introduce the behemoth-Maven [Note 3].

The build tool that can be considered for JavaScript projects is GulpJS [Note 4]. It is a plugin-based build system for which you assign tasks. The task can be "copy the .js file in the src directory to dest", or "compress my JavaScript code for production environment". What’s shocking is that GulpJS adds filters to task-related file streams, so you can add the above two tasks into one effective clean.

There are also a large number of available plug-ins. With a proper build system, you will find that collaboration in the project will be much easier.

 Conclusion

  We have only seen the tip of the JavaScript iceberg and tried to introduce some concepts and tools that Java developers should know when solving JavaScript. Naturally, there's no comprehensive list of techniques to learn here, but if you're ready to dive into a JavaScript project without looking back, this will get you started, and embracing JavaScript's quirks will help you not be frustrated as often.

 Do you know the secrets or best practices that make JS developers happy? There is no doubt that it should be shared! Comment below or chat with me on Twitter: @shelajev. I'd love to hear your thoughts!

Note 1: In computer science, tail call refers to the situation where the last action in a function is a function call: that is, the return value of this call is directly returned by the current function. In this case, the calling position is called the tail position. If this function calls itself at the tail position (or another function that calls itself at the tail position, etc.), this situation is called tail recursion, which is a special case of recursion. Tail calls are not necessarily recursive calls, but tail recursion is particularly useful and easier to implement. http://zh.wikipedia.org/wiki/Tail call

Note 2: REPL is a simple, interactive programming environment. The term is often used to refer to a Lisp interactive development environment, but can also refer to the command-line mode and programs such as APL, BASIC, Clojure, F#, Haskell, J, Julia, Perl, PHP, Prolog, Python, R, Programming languages ​​such as Ruby, Scala, Smalltalk, Standard ML, Tcl, and Javascript have similar programming environments. This is also called an interactive toplevel. http://zh.wikipedia.org/wiki/%E8%AF%BB%E5%8F%96%EF%B9%A3%E6%B1%82%E5%80%BC%EF%B9%A3%E8 %BE%93%E5%87%BA%E5%BE%AA%E7%8E%AF

Note 3: In addition to its program building capabilities, Maven also provides advanced project management tools that Ant lacks. Since Maven's default build rules are highly reusable, simple projects can often be built with two or three lines of Maven build scripts, while using Ant requires more than a dozen lines. In fact, many Apache Jakarta projects now use Maven due to its project-oriented approach, and the adoption of Maven by corporate projects continues to grow. http://www.oschina.net/p/maven

Note 4: Writing HTMLCSS Javascript from scratch is a thing of the last century. Today’s JavaScript is written through editors such as CoffeeScript that support syntactic abbreviations. If you want to use one tool to complete code cleaning and optimization after writing JavaScript, Gulp is your best choice. GulpJS is similar to Ant or Maven for Java. http://www.oschina.net/p/gulp

 Original text: javascript-explain-it-like-im-a-java-developer Translation: labazhou


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn