Improve your JavaScript level __java

Source: Internet
Author: User
Tags script tag

Original: http://bbs.ruoren.com/thread-36873994-1-1.html

************************************************************************

Objective

Today to share this article is more suitable for JS beginners, is to read and share the first phase of two children's shoes translation and proofreading, they are @ Sheng and @ White. The entire content is described in terms of modules, code reviews, and final tests.

The text starts from here ~

JavaScripts is a programming language that is easy to learn and difficult to concentrate. However, many of the content of the article is assumed that you have mastered the JS programming skills.

I started using JavaScript as a livescript in 1995, but then I gradually moved from client developers to the realm of server security. Over the last five years, I've been looking at client development again. I was pleasantly surprised to find that browsers are more powerful and easier to debug. But JavaScript starts to become complex and difficult to grasp. Recently I changed my mind, no need to master JavaScript, but I can choose to make their own JS writing level better. I'm happy to be a "good" javascript developer.

Here are some techniques and techniques I think are useful in writing JS code, such as ' Code organization ', ' Code checking ', ' testing ' and ' using browser developer Tools '. Some of them for experienced JS developers is very simple, but it is a novice very easy to develop bad habits. These specifications have helped me improve my skills and bring a better experience to my users. This is not our primary goal.

Organization

As a JS development newcomer, will inevitably put a bunch of code at the top of the HTML page. It's always easy to start with, a simple jquery that automatically focus on a form field, then it might be form validation, and then a pop box that's common in a Web page--that's the kind that interrupts people's reading so Facebook can say that they like it. After some iterations will become hundreds of lines of JS code, submerged in hundreds of lines of markup HTML document.

This is a mess, so don't do it. It sounds so simple that I don't think I need to write it down. However, when you rush to catch a quick script, it's very easy to accumulate on top of the page. To avoid this, get into the habit of creating a new JS document when you're making a website. The script tag is referenced at the same time, so you can easily add features to the interaction or other client.

Once you're out of the HTML page (there's no feeling to be more concise.) ), the next step is to organize the code. The hundreds of-line JS code may work, but you can debug or modify it after a few months, and you'll find that you're just trying to find a function.

So if simply moving some JS code from HTML to other documents is not enough, what should be done next?

Framework

It is clear that the framework is the solution. Move everything to Angularjs, Ember, react, or whatever. Rebuilding an entire Web site into a single page application or MVC can be maddening.

Or you don't need it. Don't get me wrong, I like to use angular when I do apps, but there are interactive differences between apps and Web pages. Ajax-enhancedproduct catalog and Gmail also differ-at least hundreds of lines of code are different. But if you're not going to use the framework, what are the other options?

Design Patterns

One of the things about design patterns is that "this is a summary of experiences that people can handle in the past." "They must be useful," he said. Addy Osmani wrote a book on the subject-"Learning JS design mode", you can download and read the book I recommended for free. But I have a question about this book (and a similar discussion about this topic), and you can see code like this:

In theory, design patterns are meaningful to me, but they are not. It is difficult to apply it to an actual web page context.

Module

In all the patterns I've read, I think the module pattern is the simplest and easiest to apply to existing code.

A high-level module pattern creates a closure with a simple set of code. You can use a related set of functions, put them into a module, and then select the interface you want to expose. This will create a "black box" code that is easier to apply in other projects. You can also move your code to a different document in a module.

Look at a simple example of a module pattern. I know there's a syntax at the beginning that looks strange, don't worry, let's take a look at the "container" and I'll explain the different points:

Will be puzzled by these parentheses. To be honest, even though I know JavaScript, I'm not so easy to turn around and figure out what they're doing, so I change my thinking style and start reading the code from within the code block.

Starting with a simple function, the method defined here can be called in the module.

The last pair of parentheses automatically runs the function. We will return what is defined in the function, and of course it is empty now. However, the highlighted JavaScript code is now invalid. So how to make it work.

The parentheses inside the function{make the JS statement valid. Do not believe that you can open your Developer tool console and then try to enter it yourself.

Back to the beginning ...

The last thing to do is to assign a variable to the result of the function running automatically. Although I personally fully understand the meaning of this code, every time I see this code I stop to remind myself of the meaning of this code a little bit. Sorry to mention that I kept this code in the editor so that I could copy and paste this "empty" module for quick reuse.

Now that we have understood this somewhat strange syntax, what is the real module pattern?

The code at the front creates a module called Countermodule. It consists of two functions: Incrementcounter and Resetcounter. Run to see:

The idea is to pack all the code in the Countermodule. Packaging is the entry-level thing, and future JS will provide a simpler way to do these things, but now I find that the module pattern is very simple, it is a simple and practical way to deal with organizational problems.

An example of a practical module

Let's build a simple example that can match the real situation. I speak as simply as possible, and there are scenarios that you might encounter in a real Web application.

Suppose your online gaming company Lyntendo, there is a user registration portal for users to create game identities. You need to build a table for the user to choose a name for. There are some requirements for identity rules:

The user name must begin with a capital letter.

The username must be two letters and the length of the above.

Spaces are allowed, but no punctuation marks.

User names cannot include non-mainstream words.

First, let's write a very simple table.

The above provides the table and the Submit button, but also introduced the description of the rules of the JS file, now let's look at the code.

Starting at the bottom, I use some basic code to get the elements in the page (where I'm not using jquery), and then listen to the button's Click event. Gets the value entered by the user and passes it to the validation method that I write. Verify that the value you entered conforms to the rule I described above. The code is not very complex, but when my validation rules increase and I want to add other interaction points to the page, the code becomes complicated. Let's rewrite this module.

First, create a new JS file called Game.js, followed by a script tag referenced in my index.html. Then I put the contents of the description validation logic into a module.

This is not much different from the previous one, but it is now packaged in a gamemoudule variable, and it has a valid API. Now look at the app.js.

Compared to the previous code, you can see a lot less mixing with the DOM listening code. All validated functionality (two functions and a bad word list that does not conform to validation rules) is now securely placed in the module, making the code easier to work with. In your editor, you can also complete the code module method.

Code modularity is not necessary and complex, but it is much simpler and simpler and is a very good thing.

Code checking

Code checking is useful for checking your code in practice or other issues.

Do you remember the functions you renamed and remind yourself that you're going to fix it later?

Do you remember when you defined a function to receive two parameters but ended up using only one from the beginning?

Do you remember writing some very stupid code at times? Those that can't run, like Fuction and Functon.

Code checking can help. For everyone, code checking is not just a good practice, it can be a grammar and a basic logic check. Also, using the Code Checker to help us correct the bad habit of "I know how to modify the code and then change the code when I have time". So, many modern editors have code checking plug-ins. My current editor (sublime,brackets,visual Studio code), all supported to provide real-time feedback of code detection.

For instance, this is a report of Visual Studio code. I deliberately wrote some code poorly.

Above, visual Studio code reported some of the errors in my coding. The linter of VSC, like most linters, will provide an option between what you care about and what you think is wrong ("must fix") and the warning ("Don't be lazy, fix it quickly").

If you don't want to install anything or configure your editor, you can do an online code check at jshint.com. Jshint may be the most popular Linter, based on another linter:jslint (the two are different). Jshint is much stricter than jslint. You can use Jshint directly in the editor or through the command line, of course, the easiest way to do this is to try it on a Web page.

The code on the left is a live edit, and the right side is a real-time report about the left code. Simply introducing a low-level error into your code will probably clear the flow. I changed the main function to main2:

The site immediately reported two errors. But these are not grammatical mistakes. It seems that the code above looks fine, but Jshint noticed a problem you may not be aware of (this is just a 5-line block of code, but imagine that in a large document there are functions everywhere and that the functions called are scattered across many lines, and that manual checking of code can be crazy).

So the actual example, the following code (now using jquery), is some simple JS process form validation. This trivial matter, may now half of the JS code are doing (and suddenly appear to require you to click "Like" the Modal box of this site).

This code begins with two functions to help verify age and mailboxes. Then we have a Document.ready code block to listen to the form submission. Get a value from three zones, check for whitespace (or invalid), and then the warning form is invalid or continue (or, in our case, the table does).

Let's put these in the jshint and see what we can get:

God, there are a lot of problems, but similar problems happen many times, just when you start using Linters. I did not deliberately make many unique mistakes, but repeated many of the same mistakes. The first is very simple--use strictly equal "= =" to replace "= =". This strictly tests whether the value is an empty string. Well, let's fix it first.

Here is the updated report in Jshint:

It's clear now. The next block is about undefined variables. It seems strange, if you use jquery, you will know ' $ '. The problem with Badform is simple-I forgot to set the scope for him with Var. But how do we fix $? Jshint provides a way to configure how the code checks for problems. By adding content (like annotations) to our code, we can let Jshint know that the $ variable is global and can be used with ease.

Then there is the Jshint Update report:

Ah, at last it's almost over. The final question is a good example of how jshint can provide information other than code errors. In this example, I forgot to write a function to deal with age verification. I've created the validage, but in the table check area, and it's not called. The function is only one row, but it can be used to prevent later validation, so I decided to keep it. This is the final code version (demo_jshint/app.js)

This version eventually "passed" the Jshint test. This code is not perfect yet. Now there are two validation functions, Validage and invalidemial. If validated, the return values of two validation functions are different, one is true and one is false. It would be better if the return value is consistent. Also realize that jquery will get three nodes from the DOM each time the validation runs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.