Detonate your JavaScript code evolution

Source: Internet
Author: User

          just in the program to see a section of JS code, writing extremely clever, selfish thinking if it is written according to the norms, will be able to cultivate the understanding of the language, JS programming ability to improve must be excellent. Say the words: Ya code write too messy, look at the Wohuo!

          recently leisure nothing, ready to own JS learning to do a summary. As we all know, JS is a very flexible language, 1000 people will have 1000 ways to write JS. This results in the development and maintenance of the project will leave a small hidden trouble, but also for you and the team to develop and read the code to create some difficulties, personally think good writing standards should be the first. So referring to some excellent front-end development Team code specifications, summed up a few points, hoping to let your JavaScript code up a step.

          Variable Name:

          variable names include global variables, local variables, class variables, function parameters, and so on, and they all fall into this category.

          variable naming is made up of type prefixes + meaningful words, and the use of camel-named methods increases the readability of variables and functions. For example: Susername,ncount.

          prefix specification:

          each local variable needs to have a type prefix, which can be categorized by type:

    1. S: Represents a String. For example: sname,shtml;
    2. N: Represents a number. For example: npage,ntotal;
    3. B: Representation logic. For example: Bchecked,bhaslogin;
    4. A: Represents an array. For example: Alist,agroup;
    5. R: Represents the regular expression. For example: Rdomain,remail;
    6. F: Represents a function. For example: Fgethtml,finit;
    7. O: Other objects that are not mentioned above, for example: obutton,odate;
    8. G: Represents a global variable, for example: Gusername,glogintime;
Copy Code
          of course, you can also add prefix specifications to your team and project needs, for example, our team will use:

          $: Represents a jquery object. For example: $Content, $Module;

          a more extensive naming convention for jquery object variables.

          J: Represents a jquery object. For example: Jcontent, Jmodule;

          another way to name a jquery object variable.

          fn: Represents a function. For example: Fngetname,fnsetage;

          the prefix with the above function is slightly different, instead of using FN, the individual thinks that FN can better distinguish between ordinary variables and function variables.

          DOM: Represents a DOM object, for example: Domform,dominput;

          native DOM methods and properties are used in many areas of the project, and can be adapted to the needs of the team.

          according to the project and team needs, the design of the prefix specification for the project needs, so as to achieve team development collaboration convenience.

          Exceptions:

          1: The scope of the small temporary variable can be abbreviated, for example: Str,num,bol,obj,fun,arr.

          2: Cyclic variables can be abbreviated, such as: I,j,k.

          3: Some variables that are not allowed to modify values are considered constants and all letters are capitalized. For example: Copyright,pi. A constant can exist in a function, or it can exist in a global.

          Why do you need to force the definition of a variable prefix? Formally because JavaScript is a weak language. When defining a large number of variables, we need to be very clear about what the current variable is, and it is hard to tell if it is only through ordinary words.


    1. Common code
    2. var checked = false;
    3. var check = function () {
    4. return true;
    5. }
    6. /**
    7. Some code
    8. **/

    9. if (check) {//has no way of knowing exactly whether this is going to be checked or check () causing a logic error
    10. Do some thing
    11. }

    12. Canonical post Code
    13. var bchecked = false;
    14. var fncheck = function () {
    15. return true;
    16. }
    17. /**
    18. Some code
    19. **/

    20. if (bchecked) {
    21. Do some thing
    22. }
    23. if (Fncheck ()) {
    24. Do other thing
    25. }
Copy Code
          function Name:

          unify the use of verbs or verbs + noun forms, for example: Fngetversion (), Fnsubmitform (), fninit (); functions that involve returning logical values can use words such as is,has,contains to substitute verbs, For example: Fnisobject (), Fnhasclass (), Fncontainselment ().

          If there is an intrinsic function, use the _fn+ verb + noun form, the intrinsic function must be defined at the end of the function. For example:

    1. function Fngetnumber (ntotal) {
    2. if (Ntotal < 100) {
    3. ntotal = 100;
    4. }
    5. Return _fnadd (ntotal);

    6. function _fnadd (nnumber) {
    7. nnumber++;
    8. return nnumber;
    9. }
    10. }
    11. Alert (Fgetnumber (10)); Alert 101
Copy Code
          object methods and event response functions:

          object method naming uses Fn+ object class name + verb + noun form, for example Fnaddressgetemail (), the subjective feel with the object class name slightly chicken, personally think that an object public properties and methods should be concise and easy to read. Add an object class list of words, look at unified, but a bit for the norms and norms of taste, here according to their own preferences benevolent see it.

          an event response function is named fn+ trigger event object name + Event name or module name, for example: Fndivclick (), Fnaddresssubmitbuttonclick ()

          add some common verbs to the function methods:

  1. Get get/set settings, add add/remove Delete
  2. Create creates/destory remove start start/stop stop
  3. Open on/close off, read read/write write
  4. Load load/save Save, create creates/destroy destroy
  5. Begin/end End, backup/restore restore
  6. Import imports/export export, split split/merge merge
  7. Inject injected/extract extract, attach adhesion/detach detachment
  8. Bind bind/separate Detach, view view/browse Browse
  9. Edit/modify Modify, select Select/mark tag
  10. Copy copy/paste paste, undo undo/redo Redo
  11. Insert insertion/delete Remove, add adds/append
  12. Clean cleanup/clear cleanup, index index/sort sort
  13. Find Find/search Search, increase increase/decrease decrease
  14. Play play/pause pause, launch start/run run
  15. Compile compile/execute execution, debug debug/trace Trace
  16. Observe watch/listen Monitor, build build/publish Release
  17. Input/output output, encode encoded/decode decoding
  18. Encrypt encryption/decrypt decryption, compress compression/decompress decompression
  19. Pack Pack/unpack unpacking, parse parsing/emit generation
  20. Connect connection/disconnect Disconnect, send sends/receive receive
  21. Download Download/upload upload, refresh/synchronize sync
  22. Update/revert Restore, lock lock/unlock unlock
  23. Check out checkout/check in check-in, submit submission/commit delivery
  24. Push push/pull Pull, expand expand/collapse Fold
  25. Begin Start/end end, start/finish complete
  26. Enter/exit exit, abort/quit leave
  27. Obsolete waste/depreciate waste, collect collect/aggregate gather
Copy Code
    The
          above discussed the basic JS writing naming specification, according to my personal view, as long as the code can be written in accordance with the above specifications, generally not too bad, the most incompetent no one will say you code messy difficult to read. Code specification for the maintenance of large teams is undoubtedly, of course, personal code literacy is also very helpful, I hope you can strengthen your code through the above, write easy-to-read easy to maintain code.

          the code specification belongs to tactical evolution, so let's look at how to make your JavaScript evolve strategically.

          Object-oriented writing JavaScript

          Object-oriented writing JavaScript surely you will not be unfamiliar, but I dare say that most of the front ends are generally not written by object-oriented JS code. The first is that the language mechanism of JavaScript itself makes the object-oriented writing difficult, because JavaScript is a prototype inheritance and a Class C language, his object-oriented things relative to C++/java is rather strange. The second is that JavaScript as a very flexible language, directly leading to the object-oriented writing JS and a variety of ways, so that many beginners can not tell exactly which is the correct way to write. Based on the above and personal experience, the following two writing methods are recommended:

          First Class:


    1. (function () {
    2. function Circle (Nradius) {
    3. This.nr = Nradius;
    4. }
    5. Circle.prototype = {
    6. pi:3.14,
    7. Fngetarea:function () {
    8. return this. PI * this.nr * THIS.NR;
    9. }
    10. }

    11. var C1 = new Circle (5);
    12. Alert (C1.fngetarea ()); 78.5
    13. })();
Copy Code
    The
          above can be said to be a very standard object-oriented JS writing method We also call the factory model, the advantage is simple and easy to get started, the novice often like to write. The above code changes slightly, there will be the following variant:


  1. (function () {
  2. function Circle (Nradius, smessage) {
  3. This.init.apply (this, arguments);
  4. }
  5. Circle.prototype = {
  6. Init:function (Nradius, smessage) {
  7. This.nr = Nradius;
  8. This.smessage = smessage;
  9. },
  10. pi:3.14,
  11. Fngetarea:function () {
  12. return this.smessage + ":" + this. PI * this.nr * THIS.NR;
  13. }
  14. }

  15. var c = new Circle (5, "Construction of the initialization area");
  16. Alert (C.fngetarea ()); Construction initialization Area: 78.5
  17. })();
Copy Code
    The
          above variant is more interesting, this.init.apply (this, arguments); the line of code gives the initialization task to the Init () method, and the benefit of doing so is to put all the initialized things in one place, increasing the readability , it is necessary to understand the principle of certain JavaScript operating mechanism.

          second Category:

  1. (function () {
  2. function Circle () {
  3. }
  4. Circle.prototype = {
  5. Init:function (Nradius, smessage) {
  6. This.nr = Nradius;
  7. This.smessage = smessage;
  8. },
  9. pi:3.14,
  10. Fngetarea:function () {
  11. return this.smessage + ":" + this. PI * this.nr * THIS.NR;
  12. }
  13. }

  14. var c = new Circle ();
  15. C.init (5, "manual construction of the initial area");
  16. Alert (C.fngetarea ()); Manual construction of the initialization area: 78.5
  17. })();
Copy Code
          This kind of writing is my favorite writing now, concise and efficient. From the writing point of view, the constructor initialization attribute is omitted, instead initialized in its init (). Another benefit is not to pass in the parameters at the beginning of the new Circle () construct, and personally think that when new constructs the object, it is best not to mix the parameters, which is "dangerous" and instead to "manual" initialization for easier code-troubleshooting. Of course, there is another reason for this type of writing is that he can be well converted to the generic front-end accepted "Encapsulation" code, we have the above code also slightly changed:


    1. (function () {
    2. var Circle = {
    3. Init:function (Nradius, smessage) {
    4. This.nr = Nradius;
    5. This.smessage = smessage;
    6. },
    7. pi:3.14,
    8. Fngetarea:function () {
    9. return this.smessage + ":" + this. PI * this.nr * THIS.NR;
    10. }
    11. }

    12. Circle.init (5, "package Type area");
    13. Alert (Circle.fngetarea ()); Package Size: 78.5
    14. })();
Copy Code
    Is
          not familiar with this kind of code, many of the examples on the site are written using this type of encapsulation code, the advantage is that the code is good encapsulation, can be effectively reused, more for the page functional effect implementation, encapsulating a tab control, encapsulating a marquee effect and so on. The disadvantage is that it is not good for inheritance, which is the biggest difference from the above three formats. But then again the general JS code will rarely use the inheritance, unless it is to write a large library (like Yui) will be used to inherit, generally write a function module with the encapsulation code is enough, so most front-end like to use this kind of packaging style of writing.

    The
          above introduces 2 kinds of 4 object-oriented writing, the general object-oriented write format is basically above, familiar with object-oriented writing can effectively increase your understanding of JS. Skilled use of the above 4 is also very good in the work of the Code maintenance changes to facilitate. Finally, let's talk about a technique that allows your JavaScript code to evolve in skill.

          construct objects with object literals

          an object literal is 0 or more "name/value" pairs contained in a pair of curly braces. In the object-oriented writing format, we used a lot of the object literal writing format.

          The object literal writing JavaScript can be very good to simplify the code, but also greatly increase the readability of the code, especially as a parameter can be used to corrupt as a magical performance. Let's look at the following code:


    1. (function () {
    2. function person (sName, NAge, Nweight, Bsingle) {
    3. This.sname = SName;
    4. This.nage = NAge;
    5. This.nweight = Nweight;
    6. This.bsingle = Bsingle;
    7. }
    8. Person.prototype.showInfo = function () {
    9. return this.sname + "+ this.nage +" "+ This.nweight +" "+ this.bsingle;
    10. }
    11. var p = new person ("Hai Yu", +,--);
    12. Alert (P.showinfo ()); Graceie true
    13. })();
Copy Code
    The
          above is a very standard factory model, in general, this kind of writing is the kind of code with no big mistake and no bright spots, and a lot of parameters, a careless will also pass the wrong parameters, and the application of the object literal skills can be very good to avoid such problems, we look at the changes in the code:


  1. (function () {
  2. function person () {
  3. }
  4. Person.prototype = {
  5. Init:function (option) {
  6. if (typeof option = = "undefined") {
  7. option = {};
  8. }
  9. This.sname = Option.sname | | "Sea Jade";
  10. This.nage = Option.nage | | 25;
  11. This.nweight = Option.nweight | | 75;
  12. This.bsingle = (typeof option.bsingle! = "undefined")? Option.bSingle:true;
  13. },
  14. Showinfo:function () {
  15. return this.sname + "+ this.nage +" "+ This.nweight +" "+ this.bsingle;
  16. }
  17. }
  18. var p = new person ();
  19. P.init ({
  20. NWEIGHT:80,
  21. SName: "Hank"
  22. })
  23. Alert (P.showinfo ()); Hank, True
  24. })();
Copy Code
    The
          third object-oriented style is used here, and interested friends can try to change to a wrapper. Does the rewrite above tell you where to change the most? Yes, the incoming parameter is changed to an object literal, and the incoming parameter can be set arbitrarily, and the position is reversed without any problems. The advantages of object literals are fully utilized, and the use of key-value pairs to replace the original method of communication greatly improves readability and fault tolerance. There is another improvement is the default value of the processing, if not passed any parameters, the code can also run well, there is no problem.

          Note 1: Here the formal parameter named option, did not abide by the above variable naming specification is for the convenience of writing and reading, the specific situation of specific analysis.

          NOTE 2: Due to | | Operators have assignment problems for the default assignment of Boolean values, so it is important to make a judgment whether it is undefined, and then use the ternary operator to do a good job of assigning a value to the default value of the Boolean value.

    In general, the
          above-described code evolution can only be counted on the "slim" level, want to really let code "repair Heart" or to write more, see, more practice. Only in this way will your code be more refined, more scalable, and better maintainable.

Detonate your JavaScript code evolution

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.