JavaScript is a scripting language belonging to the network!
JavaScript is used by millions of web pages to improve design, verify forms, detect browsers, create cookies, and more.
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, allowing different people to write different functions in many different ways. How to organize JavaScript code so that others can see at a glance that you are not simple? Are you looking forward to someone else sighing after reading your code, "It turns out that you can write this way"?
N ways to write anonymous functions
Js' anonymous function is a self-executing function with undeclared function name, and the format is as follows:
(function(){})();In fact, we often put ";" in front of the project:
;function(){}();Because the syntax of Js can omit semicolons, but this mechanism can also lead to unexpected errors. In order to avoid syntax errors caused by merging and compressing the code into a file after it is launched, adding ";" can avoid unknown errors.
But sometimes we see that other people's libraries or plug-ins write anonymous functions like this:
+function(){}();"+" is an operator here, and the operator has extremely high priority, so the part of the function declaration on the right with brackets (actually the way to write function execution) is executed directly. In fact, it can be not only the "+" sign in front, but operators such as "-", "!", "~", and "++" can be used. Here we are just an introduction to the extension. Which specific writing method is used depends on the unified standards of the team.
Abandon Math.ceil() and Math.floor rounding
Maybe I have seen these two symbols ~~ and |0 in other codes, and look at the running results 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 just quoted to analyze and explain this alternative writing method. A simple explanation is that ~ is a bitwise inverse operator, which can convert floating point numbers into integers by discarding all bits after the decimal point. Positive integers can be converted to unsigned hexadecimal values. Then inverse (~~) negative and negative again to get positive, and get the original integer. It’s just that he is so willful and unrestrained. Do you think it’s an optimization?
Note: If you need to do strict rounding operations, you must use this method with caution, then you still have to use the Math function.
If and else are not the only ones
Using if-else conditions is very clear logic, it doesn't look very concise when processing data is not large:
if (a===1) { //It is strongly recommended to use the strictly equal symbol "===" here, and the type conversion will not be performed a=2} else if (a===3) {a=4} else {a=5}Take a look at the following to use || and && to make the code lose weight:
((a===1)&&(true,a=2))||((a===3)&&(true,a=4))||(a=5)
It will be done in one line and you will lose weight successfully. || and &&, the simple principle is not to mention. It is not easy to understand when using the comma operator. You can continue to change it to the ternary operator:
(a===1 )? a=2:( (a===3) ? (a=4) : (a=5) )
This way of writing seems to be simplified enough, but it will be a bit difficult for others to see your code.
Replace annoying string stitching DOM structure with toString
If we want to dynamically generate a dom structure, we generally implement it like this:
var template = "<div>" + "<h2>{title}</h2>"+ "<div class='content' yAttr=''>{content}</div>"+ "</div>"If various attributes and parameters are added, it is easy to report errors when the big and small quotes are confused. However, ES6 provides Template String to help us solve this problem, you can write it like this:
var template = <div> <h2>{title}</h2> <div class='content' yAttr=''>{content}</div> </div>But the problem is that ES6 has not officially arrived yet... Don't be afraid, function.toString will solve the embarrassment when we are not connected:
var rComment = ////*([/s/S]*?)/*///;// multiply string function ms(fn){ return fn.toString().match(rComment)[1]}; ms(function(){/* <div> <h2>{title}</h2> <div class='content' yAttr=''>{content}</div> </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, prompt code B
Declare the AMD (Asynchronous Module Definition) module specification to the code you wrote, so that others can load your module directly through the AMD specification. If others do not load your module through the specification, you can also elegantly return a regular global object. Let’s take a look at the writing method of jQueryUI:
(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD mode. And rely on the plug-in "jQuery" define( [ "jquery" ], factory ); } else { // Browser global mode factory( jQuery ); } }(function( $ ) { // Put the module code here to return $.widget; }));Change it to the structure of the AMD module to make your code more suitable for browser-side loading script dependencies. Write code in this format to ensure that others know that you are a professional developer as soon as you look at the code.
The best method of inheritance
JavaScript has more than ten inheritance methods, both large and small. The advantages and disadvantages of each writing method are different, and each method is not listed one by one. Take a common inheritance method as an example, prototype inheritance:
function Parent() {}function Child() {}Child.prototype = Parent.prototypeChild.prototype.constructor = Child;This method actually points the pointer saved in Child.prototype and Parent.prototype to the same object, so if some properties are extended in the child object prototype so that the parent object prototype will continue to inherit later, the parent object prototype will also be rewritten. So to solve this problem, try to borrow a temporary constructor writing method:
function Empty(){}Empty.prototype = Parent.prototype;Child.prototype = new Empty();Child.prototype.constructor = Child;In this way, the parent object's own properties and prototype methods are protected. "Optimal" is a bit exaggerated, but in comparison. I believe that everyone has their own writing style, and there are also the advantages and disadvantages of borrowing call and apply to implement attribute inheritance. The length is limited and I will not introduce them one by one.
Summarize
All the alternative writing methods of JavaScript mentioned above are syntax sugar for easy-to-understand or improved efficiency. Such methods are preferable, such as the practice of omitting if-else as mentioned above. Some are designed to improve the compatibility and performance of our code, such as AMD and inheritance methods. ...I am a rookie, and there are certainly some incomplete and unexplained contents in the above content.
The above content is a related introduction to alternative writing methods for JavaScript, I hope it will be helpful to everyone!