JavaScript-like detection

Source: Internet
Author: User
Tags hasownproperty

First, the original (basic data: String, number, Boolean, null, undefined) types are detected.

Detect the original type with typeof: 1. For strings, typeof returns "string";

2. For numbers, typeof returns "number";

3. For Boolean type, typeof returns "Boolean";

4. For undefined,typeof return "undefined";

5. Return "Object" for null,typeof.

So detect the first four types with typeof, for the null type directly with = = = (or!) = =) detection.

Second, the detection of reference types.

Reference types are also known as objects (object), and in JavaScript, values other than the original data are references.

Because the typeof detection reference type will return "Object", it is not a good way to detect reference types.

Use instanceof to detect reference types (built-in reference types: Object, Array, Date, error, and so on): value instanceof Constructor (syntax).

Instanceof can also detect custom types in addition to detecting built-in reference types.

Third, the detection function.

There are two ways to detect a function, one is to use instanceof detection, because the function is also a reference type (object), but this method is not the best way to detect a function, because it cannot be used across frames. The second method is generally used to detect the TypeOf method.

The two ways to function MyFunc () {}console.log (typeof MyFunc = = = "function");//Good notation Console.log (myFunc instanceof  Function);//Bad wording

One limitation of using typeof to detect function types is that in IE8 and earlier versions of IE, using typeof to detect functions in a DOM node will return "object", not "function", but in other cases typeof is still the best choice for detecting JavaScript functions.

IE8 and earlier versions of IEconsole.log (typeof document.getElementById);  "Object" Console.log (typeof document.getElementsByTagName);  "Object" Console.log (typeof document.createlement);  "Object"

The safest way to detect DOM methods in IE8 and earlier browsers.

Use the in operator to detect the DOM method if ("Queryselectorall" in document) {   IMGs = Document.queryselectorall ("img");}

Four, the detection array.

An elegant solution for detecting arrays (can be used across frames).

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

 

Some browsers provide Array.isarray (value) to detect functions, as in the previous method, and can also be used across frames. The browser compatibility of this method is as follows:

 

Two methods are used together:

function IsArray (value) {   if (typeof Array.isarray = = = "function") {//Determine if there is a IsArray method in the browser       return Array.isarray ( value);  } else {    return Object.prototype.toString.call (value) = = = "[Object Array]";  }}

  

Five, detection properties.

Use in to detect if a property exists, and the in operator returns true if the attribute exists in an instance or in a prototype object. With in detection property, it simply determines whether the property exists, and does not read the value of the property.

var student = {     count:0,     related:null};//good notation if ("count" in student) {Console.log ("I am count, I will execute");} Bad notation if (student["Count"]) {//code does not execute Console.log ("I will not execute");}   Good spelling if ("related" in student) {Console.log ("I am related I will execute");} Bad notation if (student["related"] = = = NULL) {//code executes Console.log ("I will also execute");}

The above test results are as follows:

Do not try to determine whether a property exists by detecting the value of the property, as follows:

Bad wording, detect false value if (Object[propertyname]) {//Some code}//bad notation, and null compare if (object[propertyname]! = NULL) {//Some code}//bad writing, Compare with undefined if (object[propertyname]! = undefined) {//Some code}

Because when the property value of an object is a false value (0, "", false, NULL, and undefined), an error is determined using the method above.

Detects whether a property of an instance object exists, using the hasOwnProperty () method (all JavaScript objects that inherit from object have this method). In IE8 and earlier versions of IE, DOM objects are not inherited from object. So this method is not included. Therefore, you should detect the presence of a DOM object before calling the hasOwnProperty () method.

For all non-dom objects, it is good to use if (Object.hasownproperty ("related")) {   //execute the code here}//if you are not sure if it is a DOM object, you can write if ("hasOwnProperty "In Object && Object.hasownproperty (" related) ") {       //execute code here}

  

Final Summary : In addition to NULL, the other basic data types should be detected with the TypeOf method, typeof in addition to detecting the basic data types, you can also detect functions. But for IE8 and earlier browser versions, the most secure way to detect DOM functions is with the in operator; Instanceof is generally used to detect reference types, it can also detect functions, but not used across frames, so it is not a good way to detect the function of a good method or use typeof (in the case of non-IE8 and earlier browser version). Array detection Some browsers implement the method of detecting arrays-- Array.isarray (), for browsers that do not have this method, you can use Object.prototype.toString.call (value) = = = "[Object array]" to detect the array, because there are IE8 and earlier versions of IE, Checking with the In operator is a good way to determine if the properties of an instance object exist, but only when it is necessary to judge that the attribute is present in the instance object (rather than in a prototype object), the hasOwnProperty () is used. (see this article for prototype objects: Understanding prototype patterns in JavaScript)

JavaScript-like detection

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.