Type checking in JavaScript: the difference between typeof and instanceof operators

青灯夜游
Release: 2020-12-17 09:35:13
forward
2203 people have browsed it

InJavaScriptboth typeof and instanceof operators can perform type checking, so what are the differences between them? This article will introduce to you the difference between typeof and instanceof operators. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Type checking in JavaScript: the difference between typeof and instanceof operators

Related recommendations: "javascript video tutorial"

Smarties must know that JS is a weakly typed language, and variables are There are no restrictions on the type.

For example, if we create a variable using the string type, we can later assign a number to the same variable:

let message = 'Hello'; // 分配一个字符串 message = 14; // 分配一个数字
Copy after login

This dynamic gives us flexibility and simplifies variables statement.

On the downside, we can never be sure that a variable contains a value of a certain type. For example, the following functiongreet(who)requires a string parameter, however, we can call the function with any type of parameter:

function greet(who) { return `Hello, ${who}!` } greet('World'); // => 'Hello, World!' // You can use any type as argument greet(true); // => 'Hello, true!' greet([1]); // => 'Hello, 1!'
Copy after login

Sometimes we need to check the value of a variable in JS Type, what to do?

Use thetypeofoperator andinstanceofto check the instance type.

1.typeofoperator

in JS , the basic types includeString,Number,Boolean, andSymbol, etc. In addition, there are functions, objects, and the special valuesundefinedandnull.

typeofis the operator used to determine the type ofexpression:

const typeAsString = typeof expression;
Copy after login

expressionevaluates to what we want to find value of type.expressioncan be a variablemyVariable, a property accessormyObject.myProp, a function callmyFunction()or a number14.

typeof expression, depending on the value ofexpression, the result may be:'string','number','boolean','symbol','undefined','object','function'.

Let’s take a look at each type oftypeofoperator:

A) String:

const message = 'hello!'; typeof message; // => 'string'
Copy after login

B) Number:

const number = 5; typeof number; // => 'number' typeof NaN; // => 'number'
Copy after login

C) Boolean:

const ok = true; typeof ok; // => 'boolean'
Copy after login

D) Symbol:

const symbol = Symbol('key'); typeof symbol; // => 'symbol'
Copy after login

E) undefined:

const nothing = undefined; typeof nothing; // => 'undefined'
Copy after login

F) Objects:

const object = { name: 'Batman' }; typeof object; // => 'object' const array = [1, 4, 5]; typeof array; // => 'object' const regExp = /Hi/; typeof regExp; // => 'object'
Copy after login

G) Functions :

function greet(who) { return `Hello, ${who}!` } typeof greet; // => 'function'
Copy after login

1.1 typeof null

As we can see above, the result of usingtypeofto determine the object is'object'.

However,typeof nullwill also be calculated as'object'!

const missingObject = null; typeof missingObject; // => 'object'
Copy after login

typeof nullis'object'is a bug in the initial implementation of JS.

Therefore, when usingtypeofto detect objects, you need to additionally checknull:

function isObject(object) { return typeof object === 'object' && object !== null; } isObject({ name: 'Batman' }); // => true isObject(15); // => false isObject(null); // => false
Copy after login

1.2 typeof and undefined variables

Althoughtypeof expressionis usually determined by the type ofexpression, you can also usetypeofto determine whether a variable is defined.

// notDefinedVar is not defined notDefinedVar; // throws ReferenceError
Copy after login

typeofhas a nice property that whentypeofevaluates the type of an undefined variable, theReferenceErrorerror is not raised:

// notDefinedVar is not defined typeof notDefinedVar; // => 'undefined'
Copy after login

VariablenotDefinedVaris not defined in the current scope. However,typeof notDefinedVardoes not throw a reference error and instead evaluates to'undefined'.

We can usetypeofto detect whether a variable is undefined. Iftypeof myVar === 'undefined'istrue, thenmyVaris not defined.

2. instanceof operator

The usual way to use a JS function is to call it by adding a pair of brackets after its name:

function greet(who) { return `Hello, ${who}!`; } greet('World'); // => 'Hello, World!'
Copy after login

greet('World')is a regular function call.

JS functions can do much more: they can even construct objects! To have a function construct an object, just use thenewkeyword before the regular function call:

function Greeter(who) { this.message = `Hello, ${who}!`; } const worldGreeter = new Greeter('World'); worldGreeter.message; // => 'Hello, World!'
Copy after login

new Greeter('World')is to create the instanceConstructor call of worldGreeter.

How to check if JS created a specific instance using a specific constructor? Use theinstanceofoperator:

const bool = object instanceof Constructor;
Copy after login

whereobjectis the expression that evaluates the object, andConstructoris the class or function that constructs the object ,instanceofevaluates to a Boolean value.

worldGreeterThe instance is created using theGreeterconstructor, sothis worldGreeter instanceof Greeterevaluates totrue.

Starting from ES6, you can useclassto define objects. For example, define a classPetand then create an instance of itmyPet:

class Pet { constructor(name) { this.name = name; } } const myPet = new Pet('Lily');
Copy after login

new Pet('Lily')是创建实例myPet的构造调用。

由于myPet是使用Pet类构造的-const myPet = new Pet('Lily'), 所以myPet instanceof Pet的结果为true

myPet instanceof Pet; // => true
Copy after login

但是,普通对象不是Pet的实例:

const plainPet = { name: 'Zoe' }; plainPet instanceof Pet; // => false
Copy after login

我们发现instanceof对于确定内置的特殊实例(如正则表达式、数组)很有用:

function isRegExp(value) { return value instanceof RegExp; } isRegExp(/Hello/); // => true isRegExp('Hello'); // => false function isArray(value) { return value instanceof Array; } isArray([1, 2, 3]); // => true isArray({ prop: 'Val' }); // => false
Copy after login

2.1 instanceof 和父类

现在,Cat扩展了父类Pet

class Cat extends Pet { constructor(name, color) { super(name); this.color = color; } } const myCat = new Cat('Callie', 'red');
Copy after login

不出所料,myCatCat类的实例:

myCat instanceof Pet; // => true
Copy after login
Copy after login

但同时,myCat也是基类Pet的一个实例:

myCat instanceof Pet; // => true
Copy after login
Copy after login

3. 总结

JS 是一种弱类型的语言,这意味着对变量的类型没有限制。

typeof expression可以用来查看expression的类型,结果是可能是其中的一个:'string''number''boolean','symbol''undefined''object''function'

typeof null的值为'object',因此使用typeof检测对象的正确方法是typeof object ==='object'&& object!== null

instanceof运算符让我们确定实例的构造函数。 如果objectConstructor的实例,则object instanceof Constructortrue

原文地址:https://dmitripavlutin.com/javascript-typeof-instanceof/

作者:Dmitri Pavlutin

译文地址:https://segmentfault.com/a/1190000038312457

更多编程相关知识,请访问:编程课程!!

The above is the detailed content of Type checking in JavaScript: the difference between typeof and instanceof operators. For more information, please follow other related articles on the PHP Chinese website!

source:segmentfault.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!