Home >Web Front-end >JS Tutorial >Detailed explanation of the difference between instanceof and typeof operators_jquery

Detailed explanation of the difference between instanceof and typeof operators_jquery

WBOY
WBOYOriginal
2016-05-16 17:05:211147browse

1. instanceof operator:
This operator can determine whether a variable is an instance of an object (class), and the return value is of Boolean type.
To understand its function, you must have some understanding of object orientation:

The code example is as follows:

Copy code The code is as follows:

var str=new String("antzone");
console.log(str instanceof String);

The above code will output true because str is an object instance of the object String.
Generally speaking, only objects created using the constructor will return true, otherwise false will be returned. However, arrays are an exception and will return true.


2. typeof operator:
This operator can return a string to describe the type of metaarithmetic. Its return value has the following possibilities:

Copy code The code is as follows:

number,boolean,string,function,object,undefined

Let’s look at a code example:

Copy code The code is as follows:

var str=new String("antzone");
var strTwo="antzone";
console.log(typeof str);
console.log(typeof strTwo);

In the above code, the first one can output the exact type "string", but the second one is indeed "object", which is not accurate.
Generally speaking, if the operation using typeof is in the form of a direct quantity, it can return accurate results. If it is an object created using a constructor, "object" will be returned. However, there is an exception for arrays, whether it is a direct quantity or not. Return "object".

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