How to determine the type of objects in JavaScript_Basic knowledge
Recently, I was reading John Resig's masterpiece "Pro JavaScript Techniques", which talked about how to judge the type of JavaScript. The article introduces two methods, one is to use typeof, the other is to use constructor. It is a pity that as the author of jquery, he did not introduce the type judgment method used by jquery at all. But it doesn’t matter, I’ll summarize it for everyone here.
Here I first recommend to everyone a very useful online editor: http://jsfiddle.net/. It provides various versions of three mainstream js frameworks: jquery, mootools, prototype and YUI. You can use it directly when you need to write simple js test programs. This eliminates the need to open editing software and create various types of files. After editing the code, click the [Run] button and everything is done.
1.typeof
Typeof is the most commonly used method when we do type judgment. Its advantage is that it is simple and easy to remember. Its disadvantage is that it cannot judge object, null, array, regexp and custom objects very well.
The following is my test code:
var str ='str';
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'} ;
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name){
this.name=name;
}
var user=new User('user');
console.log(typeof str);
console.log(typeof arr);
console.log(typeof num);
console.log(typeof bool);
console.log (typeof obj);
console.log(typeof nullObj);
console.log(typeof undefinedObj);
console.log(typeof reg);
console.log(typeof fn);
console.log(typeof user);
Code running results:
2.constructor
Now introduce a method that is not commonly used, the object constructor constructor. Its advantage is that it supports the judgment of most object types, especially the judgment of custom objects; its disadvantage is that it cannot be used on null and undefined.
The test code is similar to the previous one, the difference is that XXX.constructor is used instead of typeof.
var str='str';
var arr =['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name) {
this.name=name;
}
var user=new User('user');
console.log(str.constructor);
console.log(arr.constructor);
console.log(num.constructor);
console.log(bool.constructor);
console.log(obj.constructor);
console.log(reg.constructor);
console.log(fn.constructor);
console.log(user.constructor);
console.log(nullObj.constructor);
console.log(undefinedObj.constructor);
When running console.log(nullObj.constructor);, the browser reports an error: Uncaught TypeError: Cannot read property 'constructor' of null. A similar problem also occurs in console.log(undefinedObj.constructor); above: Uncaught TypeError: Cannot read property 'constructor' of undefined.
3.Object.prototype.toString.call()
The last thing to introduce is the method used in jquery, Object.prototype.toString.call(). The advantage is that it supports most types of judgments, and the only disadvantage is that it does not support the judgment of custom objects.
The test code is as follows:
var str='str';
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name){
this.name=name;
}
var user=new User('user');
var toString=Object.prototype.toString;
console.log(toString.call(str));
console.log(toString.call(arr));
console.log(toString.call(num));
console.log(toString.call(bool));
console.log(toString.call(obj));
console.log(toString.call(reg));
console.log(toString.call(fn));
console.log(toString.call(user));
console.log(toString.call(nullObj));
console.log(toString.call(undefinedObj));
console.log(toString.call(user)); 的返回结果为:[object Object],不能做进一步判断。
总结
javascript中经常使用的对象判断方式包括:typeof、constructor和Object.prototype.toString.call()。其中typeof很好理解,他是JavaScript本身支持的语法。constructor很少使用,但是相信大家通过demo也能看懂他代表的意思。至于Object.prototype.toString.call()可能多少会让人有点费解,他和XXX.toString()有什么区别呢,为什么不能直接使用XXX.toString()呢?
我们在浏览器中运行下面的代码:查看运行结果:
null和undefined因为不存在toString()方法,所以会报错,我们就不去管他们了。至于其他对象,通过toString()返回的内容和使用Object.prototype.toString.call()返回的内容差别很大。这是因为Object.prototype.toString()方法被设计用来返回对象类型的。String、Array、Boolean、Regexp、Number和Function都继承自Object,同时也就继承了Object的原型方法toString(),但是他们都对toString()进行了重写。执行xxx.toString()时使用的是重写后的方法,返回的结果自然会和Object.prototype.toString.call()的结果不一致。
通过上面的例子,大家一定对这三种方式有了更深刻的认识,熟悉他们的优缺点,然后可以根据自己的需要选择合适的方式。推荐使用Object.prototype.toString.call()方法,因为他能解决绝大部分情况的判断,在遇到返回值为[object Object]时,再使用constructor辅助判断,看是否是自定义对象。
var str='str';
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;
function fn(){
alert('this is a function');
}
function User(name){
this.name=name;
}
var user=new User('user');
console.log(str.toString());
console.log(arr.toString());
console.log(num.toString());
console.log(bool.toString());
console.log(obj.toString());
console.log(reg.toString());
console.log(fn.toString());
console.log(user.toString());
console.log(nullObj.toString());
console.log(undefinedObj.toString());

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.
