Javascript Tips & Tricks

Source: Internet
Author: User

Front-end Development specification series of JavaScript tips and Tricks, intended to be written commonly used code collection, commonly used techniques to organize articles, feel "common code Daquan" Too Earth, "practical code collation" is biased, "tips and tricks" is not stable enough, so use common English parlance, Believe that the vast number of programmers understand.

Wonderful taste

The beauty of JavaScript requires a quiet experience, slowly absorbing it, and then letting the code dancing under your thumb. Sorting out the code we call the good taste, please fine products.
Bloggers will continue to update this article, convenient for everyone to read, we use the reverse update method, the latest update to put the top .

Ceshi Call function expression immediately (iife)

call function expression immediately (Iife, Immediately invoked function Expressions) is a common feature in JavaScript, and we can use it to "avoid polluting global variables", "resolve closure conflicts", "perform functions once", " Reduce the overhead of repeatedly creating larger objects (common within some tool functions, saving objects such as regular objects, arrays, long strings, etc.).

/*简化版的IIFE*/(function(){    //您的代码})();

simulate block scopes to avoid polluting global variables, as is common with plug-ins.

/* jquery1.9.0的写法 */(function( window, undefined ) {    //非常长的代码})( window );

To solve the closure conflict , we know that closures allow "functions defined inside functions to hold the execution environment of the outer function", but there may be some problems, such as the following code.

varF1 = function() {    varres = [];varFun =NULL; for(vari =0; I <Ten; i++) {fun = function() {Console.log (i);};//Generate closuresRes.push (fun); }returnRes;}//Outputs 10 10 instead of expected 0 1 2 3 4 5 6 7 8 9varres = F1 (); for(vari =0; i < res.length; i++) {res[i] ();}

We can use Iife to solve this problem, the revised code is as follows.

varF1 = function() {    varres = []; for(vari =0; I <Ten; i++) {//Add a Iife, execute now( function(index) {Fun = function() {Console.log (index);};        Res.push (fun);    }) (i); }returnRes;}//Output result is 0 1 2 3 4 5 6 7 8 9varres = F1 (); for(vari =0; i < res.length; i++) {res[i] ();}

For example , in JavaScript we can use Iife to implement OOP.

varCounter = ( function(){    vari =0;return{get: function(){            returnI }, set: function(val){i = Val; }, Increment: function() {            return++i; }    };} ()); Counter.get ();//0Counter.set (3); Counter.increment ();//4Counter.increment ();//5

mates with logical operators , such as AddEventListener's Polyfill, can write this.

/*把IIFE和逻辑运算符配合使用,检测是否需要运行polyfill*/this.Element && Element.prototype.attachEvent && !Element.prototype.addEventListener && (function () {    //polyfill}
Logical operators Magical

Use of && | | Conditional operators, we can achieve the purpose of simplifying operations, see the following code.

/ * Code one * /?if(!thetitle) {Thetitle ="Untitled Document";}//Use | |Thetitle = Thetitle | |"Untitled Document";/ * Code both * / function isadult(age) {  if(Age && Age > -) {return true;}?Else{return false; }}//Use && function isadult(age) {   returnAge && Age > -;}/ * Code three*/if(UserName) {logIn (userName);}Else{signUp ();}//Mixed use &&, | |UserName && logIn (userName) | | SignUp ();/*code four*/varUserID;?if(UserName && Username.loggedin) {UserID = username.id;}?Else{UserID =NULL;}//Use &&, | |varUserID = userName && username.loggedin && username.id
Depth

The writing process of this article is extensively referenced in the following articles, you can read the following article to get a deeper understanding.

    • Useful JavaScript Tips, Tricks and best practices
    • Simple (yet powerful) JavaScript Tips
    • JavaScript Tips & Tricks
    • JavaScript Tips and Tricks for JavaScript developers
    • Css-tricks Javascript Snippets
    • JavaScript Snippets
    • JavaScript Snippets
    • 5 Array Methods That should is Using now
    • Js-tricks
Statement

Front-end development whqet, focus on front-end development, share related resources. CSDN Expert blog, Wang Haiqing hope to help you, limited to the author level limited, error inevitably, welcome to shoot Bricks!
welcome any kind of reprint, please indicate loading, keep this paragraph text.
This article is linked in the original, http://blog.csdn.net/whqet/article/details/43865127
You are welcome to visit the Independent blog Http://whqet.github.io

Javascript Tips & Tricks

Related Article

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.