Explanation of alternative JavaScript writing, explanation of alternative javascript writing

Source: Internet
Author: User
Tags switch case

Explanation of alternative JavaScript writing, explanation of alternative javascript writing

JavaScript is a Web scripting language!

JavaScript is used by millions of web pages to improve design, validate forms, detect browsers, create cookies, and more applications.

JavaScript is the most popular scripting language on the Internet.

JavaScript is easy to use! You will love it!

JavaScript is an interpreted scripting language with flexible syntax, which allows different people to write different languages for the same function. How can we organize JavaScript code to make it easy for others to see at a glance? Are you expecting others to sigh after reading your code, "you can still write it like this?

N writing methods of anonymous Functions

Javascript's anonymous functions are self-executed functions without declaring the function name. The format is as follows:

(function(){})();

In actual projects, we often add ";" to the front:

;function(){}();

Because JavaScript syntax can omit semicolons, this mechanism can also lead to unexpected errors. To avoid syntax errors caused by merge and compression of code into a file after code goes online, adding ";" can avoid unknown errors.

But sometimes we see other people's libraries or plug-ins write anonymous functions like this:

+function(){}();

"+" Is an operator here, and the operator has a very high priority. Therefore, the function Declaration on the right side is directly executed by adding the brackets (in fact, writing the function execution method. In fact, not only the front can be "+", "-", "!" , "~" , "++" And other operators. Here is just an introduction to expansion. The specific method of writing depends on the unified standards of the team.

Discard Math. ceil () and Math. floor

You may have seen these two symbols in other codes ~~ And | 0. view the running result directly:

>> var a1 = 1.23>> ~~a11>> var a2 = 2.345>> a2|02>> var a3 = -3.45>> ~~a3-3>> var a4 = -4.5>> a4|0-4

Note that this writing method is not original, but is referenced to analyze and explain this alternative writing method. Simple explanation ,~ Is the bitwise Inverse Operator. You can convert a floating point number to an integer by rounding all the digits after the decimal point. A positive integer can be converted to an unsigned hexadecimal value. And then retrieve the inverse one (~~) If the negative value is positive, the original integer is obtained. It is so capricious that you do not like the adjustment method. It is not an optimization.

Note: If you need to use this method with caution when performing a strict rounding operation, you still need to use the Math function.

If and else are not unique either.

Using the if-else condition is a clear logic, which is not concise when the data volume is small:

If (a = 1) {// we strongly recommend that you use the symbol "= ", no type conversion is performed for a = 2} else if (a = 3) {a = 4} else {a = 5}

Look at the use | and & after slimming the Code:

((a===1)&&(true,a=2))||((a===3)&&(true,a=4))||(a=5)

One line is done, and slimming is successful. | And &, not to mention the very simple principle. It is not easy to understand the use of the comma operator in it. You can continue to replace it with the ternary OPERATOR:

(a===1 )? a=2:( (a===3) ? (a=4) : (a=5) )

The structure seems to be simplified, but it may be difficult for others to see your code.

Use toString to replace the annoying string and splice the DOM Structure

To dynamically generate a dom structure, we generally implement the following:

var template = "<div>" + "

If you add other attributes and parameters, it is easy to report errors if the quotation marks are large or small. However, ES6 provides the Template String to help us solve this problem. You can write it like this:

var template = <div> 

But the problem is that ES6 is not yet officially available... Not afraid. function. toString is used to solve the problem when we fail to answer questions:

var rComment = /\/\*([\s\S]*?)\*\//;// multiply string function ms(fn){ return fn.toString().match(rComment)[1]}; ms(function(){/* <div> 

The output here is the same as the previous string output. Front-end programmers only need to pay attention to their own dom structure.

Add AMD module support and prompt code B

The code you wrote declares the AMD (Asynchronous Module Definition) Module specification, so that others can directly load your Module through the AMD specification, if someone else does not load your module through a specification, you can return a regular global object elegantly. Let's take a look at the jQueryUI writing method:

(Function (factory) {if (typeof define = "function" & define. amd) {// AMD mode. Dependent on the define (["jQuery"], factory);} else {// global mode factory (jquery);} (function ($) {// put the module code return $. widget ;}));

Change the structure of the AMD module to make your code more suitable for loading script dependencies on the browser end. write code in this format to ensure that you are a professional developer when others read the code.

Inheritance Optimization

There are more than 10 inheritance methods, large and small, with the flexibility of JavaScript. Each method has different advantages and disadvantages, and each method is not listed one by one. For example, a common inheritance method, prototype inheritance:

function Parent() {}function Child() {}Child.prototype = Parent.prototypeChild.prototype.constructor = Child ;

This method is actually to replace Child. prototype and Parent. the pointer saved in prototype points to the same object. Therefore, if the Sub-object prototype extends some attributes so that the child object can be inherited later, the prototype of the parent object will be rewritten. To solve this problem, try to use a temporary constructor:

function Empty(){}Empty.prototype = Parent.prototype;Child.prototype = new Empty();Child.prototype.constructor = Child;

In this way, the attributes and prototype methods of the parent object are protected. The "optimum" is a bit exaggerated, but it is a comparison. I believe that everyone has their own way of writing, as well as the advantages and disadvantages of using call and apply to implement property inheritance. The length of this article is limited.

Summary

The alternative writing of all the above JavaScript statements, some of which are for the convenience of the program to understand or improve the efficiency of the syntax sugar, this approach is more desirable, for example, the above mentioned omitted if-else approach. Some are designed to improve code compatibility and performance, such as AMD and inheritance methods ....... I am a cainiao, and the above content must be incomplete and not thoroughly explained. I will try again later.

The above content is an introduction to the alternative JavaScript writing method. I hope it will help you!

Articles you may be interested in:
  • Alternative js Writing Method
  • Alternative JavaScript switch case writing
  • Alternative syntax for defining methods in Javascript (Methods for batch defining js objects)
  • Compatibility of Javascript selection
  • Javascript retains the number of digits after the decimal point
  • Js basic ajax writing example code
  • After the page is loaded, execute the jquery Writing Method of JS and the difference

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.