Home Web Front-end JS Tutorial Introduction to the difference between typeof and instanceof in JavaScript (code example)

Introduction to the difference between typeof and instanceof in JavaScript (code example)

Feb 25, 2019 am 10:25 AM
javascript principle

This article brings you an introduction to the difference between typeof and instanceof in JavaScript (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

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

typeof

typeof is a unary operation, placed before an operand, and the operand can be of any type.

The return value is a string that describes the type of the operand. (The typeof operator returns a string used to represent the data type of the expression.)

typeof is actually an instance of determining what type the parameter is. For one parameter,

typeof can generally only return The following results: "number", "string", "boolean", "object", "function" and "undefined".

The operand is a number typeof(x) = "number"

String typeof(x) = "string"

Boolean value typeof(x) = "boolean"

Object, array and null typeof(x) = "object"

Function typeof(x) = "function"

console.log(typeof (123));//typeof(123)返回"number" 
console.log(typeof ("123"));//typeof("123")返回"string"
var param1 = "string";
var param2 = new Object();
var param3 = 10;
console.log(typeof(param1)+"\n"+typeof(param2)+"\n"+typeof(param3)); 
     // string object  number
Copy after login

We can use typeof to get whether a variable exists, such as if(typeof a!="undefined"){alert("ok")}, do not use if(a) because if a does not exist (undeclared), an error will occur, for special objects such as Array and Null Using typeof always returns object. This is the limitation of typeof.

Arrays are often used in js, such as multiple inputs with the same name. If they are dynamically generated, you need to determine whether they are arrays when submitting.

    if(document.mylist.length != "undefined" ) {} //这个用法有误.
    正确的是 `if( typeof(document.mylist.length) != "undefined" ) {}` 

     或 `if( !isNaN(document.mylist.length) ) {}`
Copy after login

The operands of typeof are not Definition, the return value is "undefined".

In JavaScript, you will use the typeof operator to determine the type of a variable. When using the typeof operator, a problem will arise when using a reference type to store the value. Regardless of the reference No matter what type of object it is, it returns "object". This requires instanceof to detect whether an object is an instance of another object.

instanceof

The instanceof operator is used to test whether an object has a constructor's prototype attribute in its prototype chain.

Syntax: object instanceof constructor
Parameters: object (object to be detected.) constructor (a constructor)
Description: instanceof operator is used to detect whether constructor.prototype exists in the parameter object on the prototype chain.

instance: instance, example

a instanceof b?alert("true"):alert("false"); //a is an instance of b? True: False

instanceof is used to determine whether a variable is an instance of an object,

如 :var a=new Array();

alert(a instanceof Array); // true,

同时 alert(a instanceof Object) //也会返回 true;

这是因为 Array 是 object 的子类。



再如:function test(){};

var a=new test();

alert(a instanceof test) 会返回true

alert(a==b);  //flase
Copy after login

Case:

另外,更重的一点是 `instanceof` 可以在继承关系中用来判断一个实例是否属于它的父类型。

例如:

function Foo(){} 
Foo.prototype = new Aoo();//JavaScript 原型继承 
var foo = new Foo(); 
console.log(foo instanceof Foo)//true 
console.log(foo instanceof Aoo)//true

上面的代码中是判断了一层继承关系中的父类,在多层继承关系中,instanceof 运算符同样适用。


又如:

console.log(Object instanceof Object);//true 
console.log(Function instanceof Function);//true 
console.log(Number instanceof Number);//false 
console.log(String instanceof String);//false  
console.log(Function instanceof Object);//true  
console.log(Foo instanceof Function);//true 
console.log(Foo instanceof Foo);//false
Copy after login
// 定义构造函数
function C(){} 
function D(){} 

var o = new C();

// true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof C; 

// false,因为 D.prototype不在o的原型链上
o instanceof D; 

o instanceof Object; // true,因为Object.prototype.isPrototypeOf(o)返回true
C.prototype instanceof Object // true,同上

C.prototype = {};
var o2 = new C();

o2 instanceof C; // true

o instanceof C; // false,C.prototype指向了一个空对象,这个空对象不在o的原型链上.

D.prototype = new C(); // 继承
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true
Copy after login

Speaking of instanceof we have to insert one more question, which is function Arguments, we all may think that arguments is an Array, but if you use instanceof to test, you will find that arguments is not an Array object, although it looks very similar.

Also:

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

Got 'Y'

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

got 'N'

So, The object tested by instanceof here refers to the object in js syntax, not the dom model object.

There will be some differences when using typeof

alert(typeof(window)) will get object

It should be noted that if the expression obj instanceof Foo returns true, it does not This means that the expression will always return true, because the value of the Foo.prototype attribute may change, and the changed value may not exist on the prototype chain of obj. In this case, the value of the original expression will become false. In another case, the value of the original expression will also change, that is, the prototype chain of the object obj is changed. Although in the current ES specification, we can only read the prototype of the object but cannot change it, but with the help of non- Standard __proto__ magic properties are achievable. For example, after executing obj.__proto__ = {}, obj instanceof Foo will return false.

Example: Show that String objects and Date objects both belong to the Object type
The following code uses instanceof to prove that: String and Date objects also belong to the Object type.

例子: 表明String对象和Date对象都属于Object类型

下面的代码使用了instanceof来证明:String和Date对象同时也属于Object类型。
var simpleStr = "This is a simple string"; 
var myString  = new String();
var newStr    = new String("String created with constructor");
var myDate    = new Date();
var myObj     = {};

simpleStr instanceof String; // returns false, 检查原型链会找到 undefined
myString  instanceof String; // returns true
newStr    instanceof String; // returns true
myString  instanceof Object; // returns true

myObj instanceof Object;    // returns true, despite an undefined prototype
({})  instanceof Object;    // returns true, 同上

myString instanceof Date;   // returns false

myDate instanceof Date;     // returns true
myDate instanceof Object;   // returns true
myDate instanceof String;   // returns false
Copy after login

The above is the detailed content of Introduction to the difference between typeof and instanceof in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

In-depth discussion of the principles and practices of the Struts framework In-depth discussion of the principles and practices of the Struts framework Feb 18, 2024 pm 06:10 PM

Principle analysis and practical exploration of the Struts framework. As a commonly used MVC framework in JavaWeb development, the Struts framework has good design patterns and scalability and is widely used in enterprise-level application development. This article will analyze the principles of the Struts framework and explore it with actual code examples to help readers better understand and apply the framework. 1. Analysis of the principles of the Struts framework 1. MVC architecture The Struts framework is based on MVC (Model-View-Con

In-depth understanding of the batch Insert implementation principle in MyBatis In-depth understanding of the batch Insert implementation principle in MyBatis Feb 21, 2024 pm 04:42 PM

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

Detailed explanation of the principle of MyBatis paging plug-in Detailed explanation of the principle of MyBatis paging plug-in Feb 22, 2024 pm 03:42 PM

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

An in-depth discussion of the functions and principles of Linux RPM tools An in-depth discussion of the functions and principles of Linux RPM tools Feb 23, 2024 pm 03:00 PM

The RPM (RedHatPackageManager) tool in Linux systems is a powerful tool for installing, upgrading, uninstalling and managing system software packages. It is a commonly used software package management tool in RedHatLinux systems and is also used by many other Linux distributions. The role of the RPM tool is very important. It allows system administrators and users to easily manage software packages on the system. Through RPM, users can easily install new software packages and upgrade existing software

An in-depth analysis of the functions and working principles of the Linux chage command An in-depth analysis of the functions and working principles of the Linux chage command Feb 24, 2024 pm 03:48 PM

The chage command in the Linux system is a command used to modify the password expiration date of a user account. It can also be used to modify the longest and shortest usable date of the account. This command plays a very important role in managing user account security. It can effectively control the usage period of user passwords and enhance system security. How to use the chage command: The basic syntax of the chage command is: chage [option] user name. For example, to modify the password expiration date of user "testuser", you can use the following command

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

See all articles