An example of how to determine the type of object in JavaScript--basic knowledge

Source: Internet
Author: User

In the process of writing a JS program, you may often need to judge the type of an object, for example, you write a function, you need to judge different types of parameters to write different code.
First you might think of the typeof operator, and look at the following example:

 <script type= "Text/javascript" > 
var object = {}; 
var B = true; 
Alert (TypeOf object + "" + typeof B); 
 </script> 

The results obtained are as follows:

As you can see from the results above, the type of object can be displayed with the typeof operator, so what is the result of the typeof operator scope null and undefined?

/*var object = {}; 
var B = true; 
Alert (TypeOf object + "" + typeof B); 
/alert (typeof null + "" + typeof undefined) 

The typeof operator acts on null to show "Object" (this seems unscientific, and I thought it would show "null"), to be used for undefined to display "undefined" (this is in line with our desired result), So when you use the TypeOf operator to determine the type of an object, be especially careful because the object may be null. It just gives a partial typeof effect on these objects, and the table below lists the TypeOf operators acting on Boolean, number, String, Array, Date, RegExp, object, function, NULL, Results of undefined (interested readers can test themselves):

From the results of the table above, we can see that array, Date, regexp display is object, why not direct display object type? This leads to another operator of JS: The instanceof operator, which is used to determine whether an object is a certain type of object, evaluates to TRUE or FALSE. Let's take a look at the following:

var now = new Date (); 
var pattern =/^[\s\s]*$/; 
var names = [' Zq ', ' John ']; 
Alert (now instanceof Date) + "" 
 + (pattern instanceof RegExp) + "" + (names instanceof Array); 

It is clear that this instanceof can be used to determine the type of object, but this can only be judged by other types except the base type (which contains string types), and he cannot judge the basic type. But instanceof is not always a normal judge, consider a frame of the case, to determine the type of object is another frame passed over the object, first of all look at the following example.
Main.html

<!doctype html> 
 
 

Frame1.html

<!doctype html> 
 
 

Frame2.html

<!doctype html> 
 
 

The names object is in the frame1 frame, which is created by the array of the frame1 frame, and if the names object is compared to the array in frame2, it is obvious that names is not an instance of the array in Frame2, To think that frame1 and frame2 are not the same and array, from the 2nd realistic result can be clearly seen names is the case of his own frame, from the 3rd output can be seen frame1 array and frame2 array is different. So what happens when you encounter a comparison of the above cross frame? We can not always take the frame of the corresponding array to compare it, there is a necessary way to solve the above problem, look at the following code:

var toString = {}.tostring; 
var now = new Date (); 
Alert (Tostring.call (now)) 

{}.tostring means to get the ToString method on object objects (one of the basic methods of object objects when this method is used), and Tostring.call (now) indicates that the ToString method is invoked. Invoking the most native ToString () of the Date object (this method is the method above) method can display a string of type object date, and if it is an Array, it will produce the words [object Array]. In other words, the above operation will display the words similar to [object Class], so we just have to judge the string to know its type? This allows you to write the following tool classes:
Tools.js

 var tools = (function (undefined) {var class2type = {}, toString = {}.tostring; 
      var fun = {Type:function (obj) {return obj = = NULL | | | obj = = undefined? 
  String (obj): Class2type[tostring.call (obj)]}, Isarray:function (obj) {return Fun.type (obj) = = "Array"; 
  }, Isfunction:function (obj) {return Fun.type (obj) = = "function"; 
   }, Each:function (arr, callback) {var i = 0, haslength = arr.length? true:false; if (!callback | | (typeof callback!== ' function ') | | 
   !haslength) {return; 
    for (i = 0; i< arr.length; i++) {if (Callback.call (arr[i), I, arr[i]) = = false) {break; 
 } 
   } 
  } 
 }; Fun.each ("Boolean number String Array Date RegExp Object Function". Split (""), Function (i, name) {class2type["[Object" 
 + name + "]" = Name.tolowercase (); 
 }); 
return fun; 
})(); 

Tools provides methods such as type,isarray,isfunction to determine the type of object, and you can add a method of your own that needs to be judged according to your actual needs. Type accepts an obj parameter that returns the actual type of the object in lowercase, such as your need to determine the type of object is array, and this method returns array.
According to the tool class provided above, rewrite the example above:
fram2.html

<!doctype html> 
 
 

It is easy to determine the type of object by using the above class.
Note: Elements such as alert are not judged in IE.

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.