Home Web Front-end JS Tutorial Discussion on the use of typeof and instanceof operators in JavaScript_Basic knowledge

Discussion on the use of typeof and instanceof operators in JavaScript_Basic knowledge

May 16, 2016 pm 05:33 PM
instanceof typeof Operator

When writing JavaScript code, the two operators typeof and instanceof are used from time to time and are must-use. but! It is always difficult to get the desired results directly when using them. It is generally said that "these two operators are perhaps the biggest design flaw in JavaScript, because it is almost impossible to get the desired results from them"
typeof
Explanation: typeof returns a string of the data type of an expression, and the return result is the basic data type of js, including number, boolean, string, object, undefined, function.
Judging from the description, there seems to be no problem.

The following code writes a numerical variable, and the result after typeof is "number".

Copy code The code is as follows:

var a = 1;
console.log( typeof(a)); //=>number

If you use the constructor new of type Number to create a variable, the result after typeof is "object".
Copy code The code is as follows:

var a = new Number(1);
console.log(typeof(a)); //=>object

The above two output results seem to have no problem, which seems to be a matter of course from the book. Because javascript is designed this way.

But! The problem is that since typeof is called, it should accurately return the type of a variable, whether it is created directly with a value or with a type constructor, otherwise! What else should I use you for?
So for:
Copy the code The code is as follows:

var a = 1;
var b = new Number(1);

Accurately speaking, the types of a and b variables should be Number to get the desired result.
The accurate type information is stored in the value of the variable's internal property [[Class]], which is obtained by using the method toString defined on Object.prototype.

Get type information:
Copy code The code is as follows:

var a = 1;
var b = new Number(1);
console.log(Object.prototype.toString.call(a));
console.log(Object.prototype.toString.call(b ));

Output:
Copy code The code is as follows:

[object Number]
[object Number]

Isn’t it already very straightforward? Let’s do a little processing and get the direct result:
Copy code The code is as follows:

var a = 1;
var b = new Number(1);
console.log( Object.prototype.toString.call(a).slice(8,-1));
console.log(Object.prototype.toString.call(b).slice(8,-1));

Output:
Number
Number
This is the desired result.
For better use, we encapsulate a method to determine whether a variable is of a certain type:
Copy code The code is as follows:

function is(obj,type) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}

I have defined some variables and tested them. Let’s take a look at their typeof output first:
Copy code The code is as follows:

var a1=1;
var a2=Number(1 );
var b1="hello";
var b2=new String("hello");
var c1=[1,2,3];
var c2=new Array(1 ,2,3);
console.log("a1's typeof:" typeof(a1));
console.log("a2's typeof:" typeof(a2));
console.log(" b1's typeof:" typeof(b1));
console.log("b2's typeof:" typeof(b2));
console.log("c1's typeof:" typeof(c1));
console .log("c2's typeof:" typeof(c2));
Output:
a1's typeof:number
a2's typeof:object
b1's typeof:string
b2's typeof:object
c1's typeof:object
c2's typeof:object

使用する新しく作成した関数は次のとおりです:
コードをコピーします コードは次のとおりです:

console.log("a1 は番号:" is(a1,"Number"));
console.log("a2 は番号:" is(a2,"Number")); .log( "b1 は文字列です:" is(b1,"String"));
console.log("b2 は文字列です:" is(b2,"String")); c1 は配列 :" is(c1,"Array"));
console.log("c2 は配列:" is(c2,"Array"));
出力:
a1 は数値: true
a2 は Number:true
b1 は String:true
b2 は String:true
c1 は Array:true
c2 は Array:true


注: typeof 実際の用途は、変数が定義されているか、値が割り当てられているかを検出することです。

instanceof
説明: オブジェクトが特定のデータ型であるかどうか、または変数がオブジェクトのインスタンスであるかどうかを判断します。 instanceof 演算子も、2 つの組み込み型変数の比較に使用される場合には無力であり、結果にも満足できません。


console.log("abc"instanceof String ); // false
console.log("abc" オブジェクトのインスタンス); // 偽
console.log(new String("abc") インスタンスオブ String); // true
console.log( new String( "abc")instanceof Object); // true


カスタム オブジェクトを比較する場合にのみ関係を正確に反映します。


コードをコピーします コードは次のとおりです。
function Person() {}
function Man( ) {}
Man.prototype = new Person();
console.log(new Man()instanceofMan) // true
console.log(new Man()instanceofMan); ; // 真

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does instanceof do? What does instanceof do? Nov 14, 2023 pm 03:50 PM

The function of instanceof is to determine whether an object is an instance of a certain class, or whether it implements a certain interface. instanceof is an operator used to check whether an object is of a specified type. Usage scenarios of instanceof operator: 1. Type checking: can be used to determine the specific type of an object, so as to perform different logic according to different types; 2. Interface judgment: can be used to determine whether an object implements an interface, so as to determine whether an object implements an interface. The definition of the interface calls the corresponding method; 3. Downward transformation, etc.

Eight mysterious uses of the '!' operator in Linux commands Eight mysterious uses of the '!' operator in Linux commands Jun 27, 2023 pm 12:51 PM

Usage of most Linux commands using the '!' symbol may vary in different shells. While the examples I provide are typically used in bash shells, some other Linux shells may have different implementations or may not support certain uses of the '!' symbol at all. Let’s dive into the surprising and mysterious uses of the ‘!’ symbol in Linux commands. 1. Use the command number to run a command from the history. What you may not know is that you can run a command from the command history (commands that have already been executed). First, find the number of the command by running the 'history' command. linuxmi@linuxmi:~/www.linuxmi.

Learn more about the usage of the modulo equal operator in PHP Learn more about the usage of the modulo equal operator in PHP Mar 19, 2024 pm 12:54 PM

The modulo equal operator (%) is a very commonly used operator in PHP and is used to calculate the remainder of the division of two numbers. In this article, we will take an in-depth look at the usage of the modular equals operator and provide specific code examples to help readers better understand. First, let's look at a simple example. Suppose we need to calculate the remainder of dividing one number by another: $a=10;$b=3;$remainder=$a%$b;echo"10 divided by 3 The remainder is: &

What does instanceof mean in java What does instanceof mean in java Nov 13, 2023 pm 01:52 PM

In Java, instanceof is a binary operator used to check whether an object is an instance of a class or an instance of a subclass of a class. Its syntax is "object instanceof class", where object is an object Quote, class is a class name or interface name.

sql in operator usage sql in operator usage Aug 04, 2023 pm 03:58 PM

SQL in operator usage: 1. Single column matching, you can use the IN operator to match multiple values ​​in a column; 2. Multi-column matching, the IN operator can also be used to match values ​​in multiple columns; 3. Subquery, The IN operator can also be used with a subquery, which is a query statement nested within the main query.

Two new operators added to php7: '?->' and '??' Two new operators added to php7: '?->' and '??' Mar 21, 2023 pm 03:49 PM

In previous PHP versions, if we did not define a variable, using it directly would result in an Undefined variable error. However, in PHP7, we can use some new features to avoid this problem. These new features include two new operators: ?-> and ??. They can solve two different types of problems respectively.

How to use instanceof operator in java How to use instanceof operator in java May 19, 2023 am 08:16 AM

Concept 1. This operator is used to operate on objects and check whether the object is of a specific type (type or interface type). Format 2. If the object pointed to by the variable on the left side of the calculator is an object of the class or interface on the right side of the operator, the result is true. (Objectreferencevariable)instanceof(class/interfacetype) instance packagecom.verify_instanceof;publicclassTestInstanceOf{publicstaticvoidmain(String[]args){//The following four lines of code are used to prove: instanceof

instanceof operator in Java instanceof operator in Java Sep 01, 2023 pm 08:01 PM

This operator is only used for object reference variables. This operator checks whether an object belongs to a specific type (class type or interface type). The instanceof operator is written as -(Objectreferencevariable)instanceof(class/interfacetype) If the object referenced by the variable on the left side of the operator passes the IS-A check of the class/interface type on the right side, the result will be true. Here is an example - Example Live Demonstration publicclassTest{ publicstaticvoidmain(Stringargs[]){&nbs

See all articles