Home > Web Front-end > JS Tutorial > Give an example to explain how to determine the type of object in JavaScript_Basic knowledge

Give an example to explain how to determine the type of object in JavaScript_Basic knowledge

DDD
Release: 2023-11-24 17:56:46
Original
2003 people have browsed it

In the process of writing js programs, you may often need to determine the type of an object. For example, if you write a function, you need to write different codes by determining different parameter types.
First of all, you may think of the typeof operator. Look at the following example:

 <script type="text/javascript"> var object = {}; var b = true; alert(typeof object + " " + typeof b); </script>
Copy after login

The result obtained is as follows:

2016422170645689.png (377×220)

As you can see from the above results, the typeof operator can be used to display the type of the object. So what are the results of null and undefined in the scope of the typeof operator?

 /*var object = {}; var b = true; alert(typeof object + " " + typeof b);*/ alert(typeof null + " " + typeof undefined)
Copy after login

2016422170716617.png (239×143)

The typeof operator acts on null and actually displays "object" (this seems unscientific, I thought it would display "null'" ), acting on undefined displays "undefined" (this is in line with the result we want), so when using the typeof operator to determine the type of an object, be particularly careful because the object may be null. The above only gives a part of the results of typeof operating on these objects. The following table lists the results of typeof operator operating on Boolean, Number, String, Array, Date, RegExp, Object, Function, null, undefined (interested readers You can test it yourself):

2016422170736411.png (504×291)

From the results in the above table, we can see that Array, Date, and RegExp all display objects. Why are they not directly displaying the object type? Woolen cloth? This will lead to another operator of js: instanceof operator. This operator is used to determine whether an object is a certain type of object. The calculated value is true or false. Let’s take a look first:

 var now = new Date(); var pattern = /^[\s\S]*$/; var names = [&#39;zq&#39;, &#39;john&#39;]; alert((now instanceof Date) + " " + (pattern instanceof RegExp) + " " + (names instanceof Array));
Copy after login

2016422170805336.png (385×281)

Obviously the type of the object can be determined through this instanceof, but this can only determine other than the basic type. For other types (including String type), he cannot determine the basic type. However, instanceof cannot always be judged normally. Consider the situation of a frame. To judge whether the object of its type is an object passed by another frame, first look at the following example.
main.html

 <!doctype html> <html lang="en"> <head> <title>Main</title> </head> <frameset cols="45%,*">  <frame name="frame1" src="frame1.html"/>  <frame name="frame2" src="frame2.html"/> </frameset> </html>
Copy after login

frame1.html

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frame1</title> </head> <script type="text/javascript"> var names = [&#39;riccio zhang&#39;, &#39;zq&#39;, &#39;john&#39;]; </script> <body style="background: #ccc"> </body> </html>
Copy after login

frame2.html

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frame2</title> <script type="text/javascript"> document.write("top.frame1.names instanceof Array:"  + (top.frame1.names instanceof Array)); document.write("<br/>"); document.write("top.frame1.names instanceof top.frame1.Array:"  + (top.frame1.names instanceof top.frame1.Array)); document.write("<br/>"); document.write("top.frame1.Array === top.frame2.Array?" + (top.frame1.Array === top.frame2.Array)); </script> </head> <body style="background: #747474"> </body> </html>
Copy after login

2016422170849229.png (1365×215)

The names object is in the frame1 frame. At this time, it is created through the Array of the frame1 frame. If the names object is taken to the Array in frame2 for comparison, Obviously names is not an instance of Array in frame2. It is thought that frame1 and frame2 are not the same Array at all. From the second actual result, it can be clearly seen that names is an instance of the frame in which it is located. From the third output, it can be seen that It can be seen that the Array of frame1 and the Array of frame2 are different. So what should we do when encountering the above cross-frame comparison? We can't compare the Array corresponding to the frame every time. 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))
Copy after login

2016422170910729.png (345×186)

{}.toString means to obtain the toString method on the Object object (this method is one of the basic methods of the Object object), and toString.call(now) means to call the toString method. Calling the most native toString() method of the Date object (this method is the method on Object) can display a string of type [object Date]. If it is an Array, the words [object Array] will be generated, that is to say, perform the above The operation will display words similar to [object Class], so can we know its type just by judging the string? From this, the following tool class 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 !== &#39;function&#39;) || !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; })();
Copy after login

tools provides methods such as type, isArray, isFunction to determine the type of the object. According to the actual If necessary, you can add your own method to determine the type. type accepts an obj parameter, which returns the actual type of the object in lowercase. For example, if you need to determine the type of the object is Array, then this method will return array.
Rewrite it based on the tool class provided above The above example:
fram2.html

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>frame2</title> <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("<br/>"); document.write("top.frame1.names instanceof top.frame1.Array:"  + (top.frame1.names instanceof top.frame1.Array)); document.write("<br/>"); document.write("top.frame1.Array === top.frame2.Array?" + (top.frame1.Array === top.frame2.Array)); document.write("<br/>"); document.write("tools.isArray(top.frame1.names)?" + tools.isArray(top.frame1.names)); </script> </head> <body style="background: #747474"> </body> </html>
Copy after login

2016422171011812.png (1363×189)

At this point, the type of object can be easily determined through the above class. .
Note: Elements such as alert cannot be judged in IE.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template