The typeof and instanceof defects of JavaScript type detection and the optimization _javascript techniques

Source: Internet
Author: User
Tags object object

In JavaScript, typeof and Instanceof are two methods used to determine the comparison of data types, and the purpose of this article is to analyze the deficiencies of the two methods and propose an optimization scheme.



typeof returns a string of data types for an expression that returns the underlying data type in JavaScript, including number, Boolean, String, object, undefined, function, and 6 data types.

typeof 100; Number
typeof (1==1);//boolean
typeof ' Onepixel ';//string typeof
{};//object typeof onepixel
;// Undefined
typeof parseint;//function
typeof [];//object

As you can see, typeof can accurately determine the underlying data types other than object, but not the specific types of object types, such as Array, Date, and custom classes.



Instanceof is intended to be used to determine whether a is an instance object of B, the expression is: a instanceof B, if a is an instance of B, return true, or false. What needs special attention here is: Instanceof is the prototype, then how it is detected, we use a piece of pseudocode to simulate its internal execution process:

instanceof (a,b) = {
var L = a.__proto__;
var R = B.prototype;
The internal property of the IF (L = = = R) {
//a __proto__ the prototype object that points to B return
return false;

As you can see from the above process, when a __proto__ points to B's prototype, we think that a is the instance object of B, and we'll look at a few more examples:

[] instanceof Array; True
{} instanceof object;//true
new Date () instanceof date;//true
function person () {};
New person () instanceof person;
[] instanceof Object; True
new Date () instanceof Object;//tru

From the above example, we find that although instanceof can correctly judge [] is an Array instance object, but cannot discern [] is not object object, why, this also needs to start from the JavaScript prototype chain, we first analyze [], Array, The relationship between the three Object can be derived from instanceof: [].__proto__->array.prototype, and array.prototype.__proto__ pointed to the object.prototype,object.prototype.__proto__ point NULL, marking the end of the prototype chain. (PS: About JS prototype chain please read: Talking about JavaScript prototype and prototype chain) Therefore, [], Array, object form a prototype chain:

As can be seen from the prototype chain, [] The __proto__ eventually points to Object.prototype, and a similar new Date () and new person () also form such a prototype chain, so we use instanceof Nor is it entirely accurate to determine the specific data type of the object class.

Optimization scheme


For this problem, in reading jquery source, found a better solution, because of the source code between the mutual invocation is not easy to read and understand, therefore, according to its ideas for collation and encapsulation, the code is as follows:

(function () {
var class2type = {};
var typelist = "Boolean number String Function Array Date RegExp Object Error Symbol". Split ("");
Typelist.eacheach (function (item) {
class2type["[object" + Item + "]"] = Item.tolowercase ();
return {
getobjtype:function (obj) {
if (obj = = null) {return
obj + "";
if (typeof obj = = "Object" | | typeof obj = = "function") {
class2type[ (obj)] | | "Object"
}else {return
typeof obj;}}}
) ()

In JavaScript, typeof and instanceof are often used to determine whether a variable is empty or what type it is. But there is a difference between them:


TypeOf is a unary operation, which can be any type of operation before it is placed in one op-count.

The return value is a string that describes the type of the operand. typeof generally can only return the following results:

number,boolean,string,function,object,undefined. We can use TypeOf to get the existence of a variable, such as if (typeof a!= "undefined") {alert ("OK")}, and not to use if (a) because if a does not exist (not declared) there will be an error, for the Array,null Such special objects use TypeOf to return object, which is the limitation of TypeOf.

A small example on the Web:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http:// ">  


Instance: examples, examples

A instanceof B?alert ("true"): Alert ("false"); A is an example of B? True: false

Instanceof is used to determine whether a variable is an instance of an object, such as the Var a=new array (); alert (a instanceof array); Returns True, while alert (a Instanceof object) returns True, because the Array is a subclass of Object. Another example: function Test () {};var a=new test (); alert (a instanceof test) returns
When it comes to instanceof, we're going to insert one more question, which is the arguments of the function, and we all probably think that arguments is an array, but if you use instaceof to test, you'll find that arguments is not an array object, though it looks like it.

Other than that:

Test var a=new Array (); if (a instanceof Object) alert (' Y '); else alert (' N ');

Get ' Y '

But if (window instanceof Object) alert (' Y '); else alert (' N ');

Get ' N '

So, the object of the instanceof test here refers to the object in the JS syntax, not the DOM model object.

There are some differences between using typeof

Alert (typeof (Window)) Gets object

Do you know that the function parameter type in JavaScript is typeof or instanceof?

TypeOf can only Judge JS has several types, such as Function,object,number.

and instanceof can determine which function an object is instantiated from, such as:

var a=function (x) {};
var b=function (x) {};
var c=new a (1);
var d=new a (2);

C instanceof A is true and D instanceof B is false.

And the results of TypeOf C and TypeOf D are all object.

"Judging function parameter types" needs to choose which to use according to your needs.

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: 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.