Read the summary of chapter eighth, "Writing maintainable JavaScript"

Source: Internet
Author: User

The eighth chapter avoids "empty comparison"

Before we deal with the incoming parameters, we definitely need to verify if we want to, that is to say, in most cases, we need to compare the type.

The author first gives a code that doesn't seem to feel right:

      var Controller = {            function(items) {                 ifnull {                     //  bad notation                     Items.foreach () (function() {                         // perform some logic                      });                 }            }        };

In this code, the process () method obviously wants items to be an array because we see that items have sort () and ForEach ().

But there is a big problem with this writing: the items value can be 1, or it can be a string, or even an object, and these values are not equal to NULL, which in turn results in a problem with the subsequent execution of process (). So the next step is a variety of tests:

8.1 Detecting raw values

There are 5 primitive types in javascript: string, Number, Boolean,undefined , and null. If you want to detect them, the best way is to use the typeof operator . (Recommended by the author: typeof variable This way: typeof (Variable), but it looks like a function instead of an operator).

Basic usage:

    • For a string, typeof returns "string".
    • For numbers, typeof returns "number".
    • For Boolean values, typeof returns "Boolean".
    • Returns "undefined" for undefined,typeof.
      //Detecting Strings      if(typeofName = = = "string") {Anothername= Name.substring (3); }            //Detecting Numbers      if(typeofCount = = = "Number") {Updatecount (count); }            //Detecting Boolean values      if(typeofFound = = = "Boolean" && "found") {Message ("Found!"); }            //detection undefined      if(typeofMYAPP = = = "undefined") {MyApp= {            //the other code         }      }

the uniqueness of the typeof operator is that it is used for an undeclared variable and value without error, and they will return "undefined" through typeof.

Last primitive value: null. If the value we expect is really null, it can be compared with null:

      //  If you really need to detect null, use this method      var element = document.getElementById ("My-div");       if NULL {         = "Found";      }

Here if the DOM element does not exist, the value given by document.getElementById () is null, which either returns a node or returns NULL. Because null is a predictable output at this point, you can use!== to detect the return result.

running typeof null returns "Object", which is an inefficient method of judging null, and if you need to detect NULL, use the identity operator (= = =) or the non-identity operator (!==) directly.

8.2 Detecting Reference values

Reference values are also known as objects (object). A value other than the original value in JS is a reference. There are several built-in reference functions: Object, Array, date, and error, with a few numbers.

The typeof operator is unable to judge these reference types because all objects return "Object".

the best way to detect the type of a reference value is to use the instanceof operator . The basic syntax for instanceof is: Value instanceof constructor.

      //Detection Date      if(ValueinstanceofDate)      {Console.log (Value.getfullyear ()); }            //Detecting Regular Expressions      if(ValueinstanceofRegExp) {        if(Value.test (Anothervalue)) {Console.log ("Mathes"); }      }            //Detect Error      if(ValueinstanceofError) {         Throwvalue; }

A very interesting feature of instanceof is that it detects not only the constructor that constructs the object, but also the prototype chain. Because each object inherits from object, each object's value Instanceof object returns True.

     var New Date ();
instanceof // true instanceof // true

For this reason, instanceof is not the best way to determine whether an object belongs to a particular type.

The next author talks about: The best way to detect a custom type is to use the instanceof operator. is also the only way:

    function person (name) {         this. Name = name;     }      var New Person ("Nicholas");     instanceof // true    instanceof // true

The author later added a limitation that I did not understand, and noted here first:

This is a serious limitation: Suppose that one object in a browser frame (frame A) is passed into another frame (frame B). The constructor person is defined in both frames. If the object from frame A is an instance of the person of frame A, the following rule is true:

    // true    instanceof Frameaperson         //     instanceof Framebperson

Because each frame has a copy of person, it is considered to be an instance of a copy of someone in that frame, although both definitions may be identical.

In the end, the author explains that this problem also occurs in two other very important built-in types: functions and arrays. For them, it is generally unnecessary to use instanceof.

8.2.1 detection function

for the detection function: The best way is to use typeofbecause it can be used across frames (frame):

     function MyFunc () {}           // good wording.     Console.log (typeof//  true

The author adds--(this time because of IE): There is a limit to using TypeOf to detect functions. In IE8 and earlier versions of IE, the functions in TypeOf to detect DOM nodes (such as document.getElementById ()) return "object" instead of "function".

    //  IE8 and earlier versions of IE    console.log (typeof document.getElementById);  // "Object"    Console.log (typeof document.createelement);  // "Object"    Console.log (typeof document.getElementsByTagName);  // "Object"

This problem is the legacy of early ie, developers often use the in operator to detect the DOM method:

     // detecting DOM Methods     if inch document) {         = Document.queryselectorall ("img");     }

This code checks to see if Queryselectorall is defined in document, and if so, this method. Although not the ideal approach, it is safest to detect the presence of DOM methods in IE8 and earlier browsers. In all other cases, the TypeOf operator is the best choice for detecting JavaScript functions.

8.2.2 Detecting Arrays

ECMASCRIPT5 will formally introduce Array.isarray () into JavaScript. The only purpose is to accurately detect whether a value is an array.

The Array.isarrary () method is implemented for (ie9+, SAFARI5, Opera 10.5+, and Chrome).

Prior to this, there was an elegant solution:

function IsArray (value) {       return Object.prototype.toString.call (value) = = = "[Object Array]";    }

By merging the two methods, most class libraries implement this method in a similar way:

function IsArray (value) {       if (typeof Array.isarray = = = "function")          {return  Array.isarray (value);        Else {          return Object.prototype.toString.call (value) = = = "[Object Array]";}    }
8.3 Detection Properties

The best way to determine properties is to use the in operator. The in operator simply determines whether a property exists and does not read the value of the property.

The third chapter also says that the in operator traverses the prototype chain. If you only want to traverse the instance object, use hasOwnProperty ()

All JavaScript objects that inherit from object have this method.

The author adds an exception (ie again). Drunk): In IE8 and earlier versions, Dom objects are not inherited from object, and therefore do not contain this method. Therefore, you should detect the presence of a DOM object before calling the hasOwnProperty () method (if you already know that the object is not DOM.) This step can be omitted).

    //  for all non-dom objects, this is a good notation    if (Object.hasownproperty ("realted")) {        //  Execute the code here     }       //  If you are not sure if you are a DOM object, you can write if in     object && object.hasownproperty (" Related ")) {        //  Execute the code here    }

Read the summary of chapter eighth, "Writing maintainable JavaScript"

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.