JS's judgment on basic types and reference types

Source: Internet
Author: User
Tags array example

So long-winded wrote a lot, the original few words can be confessed to the things that are so lengthy.

But when I was confused about the problem, I wanted to find the explanation that I knew and knew it.

Confined to their own knowledge and the length of the article, I can not tell how meticulous, not even guarantee correctness.

I can only put my own understanding of JS to write, we can judge to see.

Anxious to find the answer to the friend can directly turn to the back to see summary.

------------------------------------------------------------------------------------------------------------

Detection of basic types:

JS has 6 basic types of data:

Undefined, Null, Boolean, number, String, and a relatively complex Object.

Where Undefined and Null are special: There is only one value, which means "none", but the former represents undefined and the latter represents a null pointer (object).

If you use the typeof operator to detect 6 types of values:

typeofUndefined//get "undefined"typeof NULL;//get "Object"typeof false;//get "boolean"typeof(1);//get "number"typeof "Str";//get "string"typeof{};//get "Object"    


You will find that typeof null gets not "null" but "object".

Technically null belongs to object because it contains an object pointer. However, unlike normal object pointers, this pointer does not point to any object. It exists and does not exist, and JS uses it to describe a "object that has not existed or will not exist". Because NULL is special in the object type, JS makes it a new type independent of the normal object type, and because it is associated with the nature of object, its typeof result is "Object".

When it comes to particularity, function is also an object with particularity.

It belongs to the object (JS is an object-oriented language, in addition to the basic type, nature is the object), but not limited to objects, or even higher than the object. The function is used to describe "behavior", which can be a specific behavior of an object, and can refer to the behavior of the whole program. It has its own special properties and how it is applied, and is therefore different from other objects.

Null is also a special object at best, so typeof null = = = "Object", and the function is detached from object because of its particularity, so

typeof (function () {});        // get "function"


The function has its own special identity "function", not "object".


To judge a reference type:

JS is an object-oriented language, and the encapsulation and use of objects is essential.

For specific objects, if you still use typeof, you often don't get the results you want, such as:

typeof New Array ();                   // get "Object" instead of "array" typeof New Date ();                    // get "Object" instead of "date". 

The results may differ from what you might expect, but not directly wrong-arrays and regular are really objects, what's wrong with that?

The result, I personally think is because TypeOf is only responsible for telling you the general direction of what this type, so the face of an object when it will only tell you that this is an object, regardless of the object's name-"array" and "date" is really a name, they can be " Brray "and" Cate ", JS is not limited to what the object is called (especially the custom object), it is only OK to determine, the uncertainty will give a although general but still can ensure the correct answer, this design is reasonable.

The typeof operator is used only to detect basic types and functions and is no longer responsible for judging specific reference types.

So how do you judge the type of a specific object?

With the instanceof operator:

    var New Array ();     instanceof Array;                    // Get True    function Sup () {}     var New Sup ();     instanceof Sup ();                     // gets true, which can be correctly detected for custom objects. 


Or use the constructor property of the object

 var  arr = new   array (); Arr.constructor  = = = Array; //  get True  function   Sup () {}  var  S1 = new                     sup (); S1.constructor  = = = sup; //  

The

Two methods appear to be consistent, but there are different drawbacks:

instanceof is used to detect whether an object is an instance of an object prototype, normally (in the same domain) var arr = new Array (), and arr is naturally an array example, the test results are of course accurate. But in specific applications where cross-domain issues are involved, such as having a different frame in a Web page, the code needs to be run in a different frame. You should pay attention when using instanceof. Because each frame has its own window (Global) object, each window has its own array object, which, although it has the same name, does not point to the same object. In fact, the truth is simple: in China you say home in the capital, who all know refers to Beijing. In the United States if you talk to people about home in the capital, people will think you're talking about Washington. The capital (object prototype), while having the same name, points to a different location (object) in a different domain (frame).

As for the constructor problem, it returns a "constructor for the current object". Not only is there a cross-domain problem, but it may also result from an inadvertent failure to implement an object's inheritance:
      

function Super () {} function  New  Super (); // Sub.prototype.constructor = Sub;        Unless specified here, the next code result is false.  New Sub (). constructor = = = Sub;

The workaround is not not:

First, JS provides a Array.isarray () method for the array type, but requires ie9+, firefox4+, safari5+, Chrome, or opera10.5+ version support and is not adaptable.

In addition, functions are used on browsers other than IE. name is also a good method, but not recommended:

Arr.constructor.name = = = "Array";

Finally, the book also provides a cross-domain approach:

Object.prototype.toString.call (object). IndexOf ("Object prototype") >= 0; var type = Object.prototype.toString.call (arr); Type gets "[Object array]", and then the "array" in the string is judged.

However, this method cannot be used on a custom object, it returns "[Object Object]" for all custom objects. For this we can only retreat and beg the second to use the instanceof operator, fortunately, it is rare to encounter this problem, pay attention to the line.

Summarize:

1, for 6 basic types and Function reference type judgment: Use the TypeOf operator can be competent.

2, to JS built-in reference type judgment: Using the Object.prototype.toString.call () method to avoid cross-domain problems

3, for custom types, you can only use instanceof.

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.