How to determine the js object type

Source: Internet
Author: User

How to determine the js object type

When writing javascript programs, you may often need to determine the type of an object. For example, if you write a function, you need to compile different codes by judging different parameter types.

First, you may thinkTypeofSee the following example for the operator:

 

  <script type=text/javascript>var object = {};var b = true;alert(typeof object +   + typeof b);  </script>
The result is as follows:

 

As shown in the preceding resultTypeofThe operator can display the object type. So what are the results 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 display "object" (This seems unscientific, I thought it would display "null'"), when undefined is used to display "undefined" (This meets the expected result), be especially careful when using the typeof operator to determine the type of an object, because this object may be null. The above only gave some typeof results for these objects. The following table lists the effects of the typeof operator on Boolean, Number, String, Array, Date, RegExp, Object, Function, null, undefined result (interested readers can test it on their own ):

From the results in the above table, we can see that Array, Date, and RegExp all display objects. Why not directly display the object type? This leads to another js OPERATOR:InstanceofThis operator is used to determine whether an object is of a certain type. The calculated value is true or false. Let's take a look at the following:

 

var now = new Date();var pattern = /^[sS]*$/;var names = ['zq', 'john'];alert((now instanceof Date) +   + (pattern instanceof RegExp) +   + (names instanceof Array));

 

Obviously, this instanceof can be used to determine the object type, but this can only be used to determine other types except the basic type (including the String type). It cannot be used to determine the basic type. However, instanceof is not always normal. In the case of a framework, it is necessary to determine that an object of its type is an object transmitted by another frame. First, let's look at the following example.

Main.html

 

 Frame1.html 

 

 

  <Script type = text/javascript> var names = ['riccio zhang ', 'zq', 'john']; </script> 

Frame2.html

 

 

   <Script type = text/javascript> document. write (top. frame1.names instanceof Array: + (top. frame1.names instanceof Array); document. write ( 

); Document. write (top. frame1.names instanceof top. frame1.Array: + (top. frame1.names instanceof top. frame1.Array); document. write (
); Document. write (top. frame1.Array = top. frame2.Array? + (Top. frame1.Array === top. frame2.Array); </script>

 

The names object is in the framework of frame1. at this time, it is created through the Array of the framework of frame1. if the names object is taken to the Array in frame2 for comparison, it is clear that names is not an Array instance in frame2, I think that frame1 and frame2 are not the same and Array at all. From the 2nd realistic results, we can see that names is an instance of its own frame, from the 3rd output, we can see that the Array of frame1 is different from the Array of frame2. What should we do if we encounter the above cross-frame comparison? We can't always compare them with the Array corresponding to the framework. There is a necessary way to solve the above problem. Let's look at the following code:

 

   var toString = {}.toString;   var now = new Date();   alert(toString.call(now))

 

{}. ToString indicates to obtain the toString method on the Object (one of the basic methods of the Object in this method), and toString. call (now) indicates to call the toString method. Call the Date Object's most native toString () (this method is the method above the object) method to display a string of the [Object Date] type, for example, Array, [object Array] is generated. That is to say, the above operation will display a word similar to [object Class]. so we only need to judge this string and will not know its type? The following tool classes can be written:

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, and isFunction to determine the object type. You can add methods to determine the type based on actual needs. Type accepts an obj parameter, which returns the actual type of the object in lowercase. For example, if you need to determine that the object type is Array, this method will return array.

 

Based on the tool class provided above, rewrite the above example again:

Fram2.html

 

  <Script type = text/javascript src = tools. js> </script> <script type = text/javascript> document. write (top. frame1.names instanceof Array: + (top. frame1.names instanceof Array); document. write ( 

); Document. write (top. frame1.names instanceof top. frame1.Array: + (top. frame1.names instanceof top. frame1.Array); document. write (
); Document. write (top. frame1.Array = top. frame2.Array? + (Top. frame1.Array === top. frame2.Array); document. write (
); Document. write (tools. isArray (top. frame1.names )? + Tools. isArray (top. frame1.names); </script>

 

So far, the above class can easily judge the object type.

Note: in IE, elements such as alert cannot be judged.

 

 

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.